-
Notifications
You must be signed in to change notification settings - Fork 19
/
Listener.java
52 lines (44 loc) · 1.08 KB
/
Listener.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
51
52
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Listener thread that keeps listening to a port and asks talker thread to process
* when a request is accepted.
* @author Chuan Xia
*
*/
public class Listener extends Thread {
private Node local;
private ServerSocket serverSocket;
private boolean alive;
public Listener (Node n) {
local = n;
alive = true;
InetSocketAddress localAddress = local.getAddress();
int port = localAddress.getPort();
//open server/listener socket
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
throw new RuntimeException("\nCannot open listener port "+port+". Now exit.\n", e);
}
}
@Override
public void run() {
while (alive) {
Socket talkSocket = null;
try {
talkSocket = serverSocket.accept();
} catch (IOException e) {
throw new RuntimeException(
"Cannot accepting connection", e);
}
//new talker
new Thread(new Talker(talkSocket, local)).start();
}
}
public void toDie() {
alive = false;
}
}