Reputation: 30568
Here is the code:
TaskA a = new TaskA(this.serverSocket, this.socket);
a.assignConfig(this.config);
this.threada = new Thread(a);
this.threada.start();
TaskB b = new TaskB(this.serverSocket, this.socket);
b.assignConfig(this.config);
this.threadb = new Thread(b);
this.threadb.start();
In TaskA, this class work like that:
if (this.serversocket == null) {
this.serversocket = new ServerSocket(this.config.getI_respondPort());
}
if (this.serversocket != null) {
System.out
.println("this.serversocket " + this.serversocket);
}
this.serversocket.setSoTimeout((int) this.config
.getL_respondSocketInterval());
while (this.is_keepRun()) {
System.out.println("Keep Listening");
Thread.sleep(this.config.getL_heartBeatInterval());
}
And the TaskB is like this:
while (this.is_keepRun()) {
if (this.serversocket != null) {
System.out.println("waiting input");
this.socket = this.serversocket.accept();
System.out.println("Connection received from "
+ this.socket.getInetAddress().getHostName());
}
}
I assign the same serverSocket and socket via their own constructor, but when the socket got the connection, TaskA can do the serversocket.accept
, but the TaskB's serversocket is always null, wt did I do wrong? Thanks.
Upvotes: 1
Views: 122
Reputation: 4691
ServerSockets are looking for new socket connections, and block on a given port. If you want multiple server sockets use multiple ports. If you want multiple threads on various sockets, then use one server socket, and have a thread to do the work once its created. The accept is just waiting for one to be created, see here for a good basic intro to sockets: http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html
Upvotes: 2