【发布时间】:2014-10-21 00:59:49
【问题描述】:
我正在编写一个多线程服务器,它目前只接收一个字符串并将其发送回大写。
我的问题是服务器没有检测到与客户端的连接何时丢失,因此客户端处理程序线程一直在运行。
我有一个处理客户端请求的 while 循环,如果连接关闭/丢失,我想跳出这个循环。
这是ClientHandler的代码
try {
inFromServer = clientSocket.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
OutputStream outToServer = clientSocket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
while(!clientSocket.isClosed()){
if(in.available() > 0) {
String str = in.readUTF(); //Should catch EOF
System.out.println("[+] From " + clientSocket.getInetAddress() + " received: " + str);
String response = str.toUpperCase();
out.writeUTF(response);
}
}
System.out.println("[+] Closing client");
} catch (IOException e) {
e.printStackTrace();
}
我尝试过这样循环:
while(!clientSocket.isClosed() && inFromServer.read() != -1)
但这不起作用...
任何建议将不胜感激。
【问题讨论】:
-
我不认为你可以,这就是为什么某些协议(如 IRC)会定期 ping 他们的客户端并等待超时的答案。
-
Socket.isClosed()检测到一个关闭的 socket 没问题,但你真正要问的是一个关闭的 connection,由对等方关闭。 @jtahlborn 的回答是正确的。
标签: java multithreading sockets serversocket