我正在编写一个服务器-多Thread客户端通信应用程序,我需要制作一个循环并接受客户端。我目前的代码是:
Thread acceptor = new Thread() {
public void run() {
while(true){
System.out.println("looking for clients");
try{
Socket s = serverSocket.accept();
clientList.add(new ConnectionToClient(s));
}
catch(IOException e){ e.printStackTrace(); }
}
}
}
};
acceptor.setDaemon(true);
acceptor.start();
Run Code Online (Sandbox Code Playgroud)
但是,当我运行我的应用程序时,文本looking for clients只出现一次,并且没有客户端可以连接。
我不明白为什么我的while(true)循环实际上没有循环,并且只运行一次。
编辑:
该ConnectionToClient构造函数是:
ConnectionToClient(Socket socket) throws IOException {
this.socket = socket;
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
Thread read = new Thread(){
public void run(){
while(true){
try {
Object obj = in.readObject();
messages.put(obj);
} …Run Code Online (Sandbox Code Playgroud)