[英]Communicating between one ServerSocket and several Sockets
我试图让我的ServerSocket与多个Socket通信,但我不知道如何,到目前为止我意识到调用serverSocket.accept()将返回一个套接字在服务器和第一个套接字之间进行通信,但是当第二个和之后正在尝试连接到ServerSocket,它让它们连接,但没有得到一个新的套接字与它们通信,所以,我如何与第二个Socket进行通信?
Simply put, you need to spawn a new thread if you want to communicate with both sockets at the same time. 简单地说,如果要同时与两个套接字通信,则需要生成一个新线程。
ServerSocket ss = new ServerSocket(... params ...);
while(isRunning) {
Socket socket = ss.accept();
Runnable r = new SocketHandler(socket); // write the socket handler class
Thread t = new Thread(r);
t.start();
}
Now obviously there are many, many improvements you can make to this. 现在很明显,你可以做很多很多改进。 The most obvious would be holding on to the references of r and/or t so you have better/tighter control over them, and the ability to stop them at will.
最明显的是坚持r和/或t的引用,这样你就可以更好/更严格地控制它们,并且能够随意停止它们。 But those features are well beyond the scope of this question.
但这些功能远远超出了这个问题的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.