简体   繁体   中英

How to keep Java Client Socket alive when network connection drops?

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();
    }

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...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM