Reputation: 13
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();
}
Upvotes: 1
Views: 286
Reputation: 441
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...)
Upvotes: 1