如何处理客户意外断开连接。我想保持服务器运行/监听,除非客户明确说明关闭。
例如,我的服务器正在侦听,然后关闭客户端,导致服务器的方法结束 - 如何让它返回到方法的开头呢?
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BasicProtocol bp = new BasicProtocol(password);
out.println(bp.processInput(""));
String inputLine;
while((inputLine = in.readLine()) != null ){
System.out.println("Client asks: " + inputLine);
out.println(bp.processInput(inputLine));
}
如上所述,如果发生连接重置错误,它怎么能等待重新连接到?
答案 0 :(得分:1)
例如,您可以在方法中使用一个boolean变量,该变量在客户端要关闭时更改。就这样:
boolean isRunning = true;
while (isRunning) {
//Your current method - when client wants to disconnect just set isRunning = false;
}