英文:
How to keep Java Client Socket alive when network connection drops?
问题
经常在我的互联网连接中断几秒钟后,我不得不重新启动客户端应用程序。我是否需要在每次断开连接时创建新连接,还是有一种方法可以在“等待”的同时保持客户端套接字保持活动状态,直到重新建立连接?我不确定断开连接的确切时间。当我们尝试写回输出流时是否会断开连接,因为readLine()可能能够挺过断开连接?还是“&& !kkSocket.isClosed()”的检查多余并且会关闭while循环?提前谢谢。
try {
kkSocket = new Socket("12.345.67.899", 1234);
out = new PrintWriter(kkSocket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
return;
}
try (
BufferedReader in = new BufferedReader(
new InputStreamReader(kkSocket.getInputStream()));
) {
String fromServer;
while ((fromServer = in.readLine()) != null && !kkSocket.isClosed()) {
doSomething(fromServer);
out.println("返回给服务器");
}
} catch (IOException e) {
Thread.currentThread().interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
英文:
I often have to restart my client application when my internet connection goes down for a few seconds. Do I have to create new connection on every disconnect or is there a way to keep client socket alive while "waiting?" for connection to be reestablished? I am not sure when exactly the disconnect happens. Is it when we try to write back to the outputstream as readLine() might be able to survive the disconnect? Or is the "&& !kkSocket.isClosed()" check redundant and closes the while loop? Thanks in advance.
try {
kkSocket = new Socket("12.345.67.899", 1234);
out = new PrintWriter(kkSocket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
return;
}
try (
BufferedReader in = new BufferedReader(
new InputStreamReader(kkSocket.getInputStream()));
) {
String fromServer;
while ((fromServer = in.readLine()) != null && !kkSocket.isClosed()) {
doSomething(fromServer);
out.println("Back to server");
}
} catch (IOException e) {
Thread.currentThread().interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
答案1
得分: 1
这里不可能使客户端套接字“等待”连接重新建立。您可以的做法是创建一个循环,断开连接后将尝试重新连接服务器,例如基于定时器(每隔X秒)。这样,您就可以避免手动重新启动应用程序。
请注意,您需要实现某种退出此重试循环以退出程序的方式(例如:抛出键盘事件,在连续X次尝试未成功后退出等…)。
英文:
It is not possible to make a client socket "wait" for the connection to be reestablished. What you can do instead is creating a loop that will retry to connect to the server upon disconnect, for example based on a timer (every X seconds). This way you avoid having to manually restart your application.
Note that you would have to implement some way of exiting this retry loop to exit your program. (ex: throw a keyboard event, exit after X consecutive unsuccessful attempts etc...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论