-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNodeListener.java
50 lines (47 loc) · 1.59 KB
/
NodeListener.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.lang.Thread;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class NodeListener extends Thread {
Node node;
int port;
private ServerSocket serverSocket;
public NodeListener(Node node, int port) throws IOException {
this.node = node;
this.port = port;
serverSocket = new ServerSocket(port);
}
@Override
public void run() {
while (true) {
try {
Socket server = serverSocket.accept();
ObjectInputStream in = new ObjectInputStream(server.getInputStream());
Message msg = (Message) in.readObject();
this.node.receiveMsg(msg);
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
} catch (IOException e) {
e.printStackTrace();
break;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (this.node.ifMAPStop || this.node.terminate) {
System.out.println("++++++++++++++ Node " + this.node.nodeID + " listener thread stop...");
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
}
}
}