我是套接字编程新手,正在尝试编写一个简单的命令行聊天应用程序。 现在我使用下面的代码来接受连接,然后为其创建一个新线程,但不会创建新线程,并且不支持多个客户端(这在不使用线程时通常是这样),
public class chatserver extends Thread{
public static Socket client;
public static void main(String a[]) throws Exception{
ServerSocket srv = new ServerSocket(4444);
if((client = srv.accept())!=null){
new newthread(client);
}
}
}
class newthread extends Thread{
private Socket client;
public newthread(Socket client){
super("chatchild");
this.client = client;
start();
}
为什么没有创建线程?我在“oracle.com”上提供了示例,其中一个包含相同的代码,但我无法弄清楚将发生什么以及何时发生的确切顺序???来自的片段接受连接并创建线程的示例代码::
while (listening)
new KKMultiServerThread(serverSocket.accept()).start();
现在这里的监听是 bool var sat 为 true,但它在代码中的任何地方都不会设置为 false。???这是如何工作的?
最佳答案
您必须不断调用accept()来创建其他线程:
public static void main(String a[]) throws Exception{
ServerSocket srv = new ServerSocket(4444);
while (listening) {
new newthread(srv.accept());
}
}
如果您想停止服务器,listening 变量应设置为 false。
关于java - 为什么不创建单独的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6560567/