由於某些原因,當我運行我的服務器代碼時,服務器窗口彈出,但然後它凍結,並且不允許我做任何事情。我用我的代碼進行了實驗,似乎while
循環是問題所在,因爲當我刪除它時,它工作正常。但我需要while
循環爲許多客戶端提供服務。以下是代碼:試圖在Java中製作多個客戶端服務器?
注意:變量numClients
已被初始化並在其他地方實例化。
try{
ServerSocket serverSocket = new ServerSocket(8000);
textArea.append("Server started on " + new Date() + "\n");
while(numClients <= 5){
Socket socket = serverSocket.accept();
InetAddress inetAddress = socket.getInetAddress();
textArea.append("Client \"" + inetAddress.getHostName() + "\" has
connected!");
textArea.append("The IP address of \"" + inetAddress.getHostName() +
"\" is " + inetAddress.getHostAddress());
HandleClient task = new HandleClient(socket);
new Thread(task).start();
numClients++;
}
}
catch(IOException ex){
ex.printStackTrace();
}