我有一个要求,我需要一次打开两个ServerSockets并连续监听它们各自的套接字。
这些工作正常,但我需要一起工作。
while(true){
Socket socket = serversocket1.accept()
new SocketProcessor(socket).start();
}
while(true){
Socket socket = serversocket2.accept()
new AnotherSocketProcessor(socket).start();
}
我该怎么做?
答案 0 :(得分:1)
您可以在此处参考。你必须使用多线程......
Listening to two ports simultaneously in Java server using multithreading
答案 1 :(得分:0)
您考虑过多线程吗?
首先,我们创建一个实现Runnable接口的类。
class SocketListenerRunnable implements Runnable {
ServerSocket serverSocket;
SocketProcessor socketProcessor;
public void setServerSocket (ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
public void setSocketProcessor (SocketProcessor socketProcessor) {
this.socketProcessor = socketProcessor;
}
public void run () {
while (true) {
Socket socket = serverSocket.accept ();
socketProcessor (socket).start ();
}
}
}
然后我们只在需要时使用它。
SocketListenerRunnable r1 = new SocketListenerRunnable ();
r1.setServerSocket (serverSocket1);
r1.setSocketProcessor (socketProcessor1);
Thread t1 = new Thread (r1);
t1.start ();
SocketListenerRunnable r2 = new SocketListenerRunnable ();
r2.setServerSocket (serverSocket2);
r2.setSocketProcessor (socketProcessor2);
Thread t2 = new Thread (r2);
t2.start ();