保持(单线程)服务器套接字在意外的套接字关闭时监听客户端 [英] Keeping a (single threaded) server socket listening for clients on unexpected socket closure
问题描述
如何处理客户意外断开连接。我想保持服务器运行/监听,除非客户明确说明关闭。
How should one deal with clients disconnecting unexpectedly. I want to keep the server running/listening unless explicitly stated to close by the client.
例如,我的服务器正在侦听,然后关闭客户端导致服务器的方法结束 - 如何让它返回到方法的开头它是?
For example, my server is listening and then the client is closed which causes the server's method to end - how can I get it to return to the beginning of the method as it were?
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));
}
如上所述,如果发生连接重置错误,它怎么能等待重新连接to?
As above, if a connection reset error occurs how can it wait to be reconnected to?
推荐答案
例如,你可以在方法中使用一个boolean变量的while循环,当客户想要更改时关。因此:
For instance you can have a while loop at the method with a boolean variable that is changed when the client wants to close. As such:
boolean isRunning = true;
while (isRunning) {
//Your current method - when client wants to disconnect just set isRunning = false;
}
这篇关于保持(单线程)服务器套接字在意外的套接字关闭时监听客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!