How do I reconnect a client when server is down in Java?

Bojje picture Bojje · Mar 12, 2015 · Viewed 7.8k times · Source

I have a server that accepts sockets from whenever a client connects. I want to be able to shutdown my local server and let my client try to reconnect for about 5 times, and if I start my server the client should indicate that you have reconnected again.

I understand somewhat that this is done in the try{} catch(IOException){Here goes the code for handleing reconnect} I want to use the same socket that I first used to connect. I don't want to create a new Client cause then I have to enter username and stuff like that all over again

I tried to creating a new socket like clientSocket = new Socket("localhost", portnr) but I don't know if this is the correct way to go. If you have examples that answers this please link them. I dont mind reading as long as it is good documented. Thanks in advance!

EDIT. Here is my Client Class

public class Client {       

public static void main(String[] args) {        
    Client client = new Client();
    client.connect();
}
//------------------------------------------------------------

//METHOD CONNECT
//------------------------------------------------------------    
private void connect(){
    int reConnectTries = 0;
    Socket clientsocket;
    try {
        //------------------------------------------------
        //Sets up variables needded for execution            
        clientsocket = new Socket("localhost", 8900);
        DataOutputStream OUT = new DataOutputStream(clientsocket.getOutputStream());            
        ListenforMessages listen = new ListenforMessages(clientsocket);
        //We don't want to enter username all the time
        //So this goes not in the while-loop
        //------------------------------------------------
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter username");
        String username = keyboard.nextLine();
        //Sends username to sever so it can be added to a list
        OUT.writeUTF(username);
        //------------------------------------------------

        //------------------------------
        //Creates a thread to listen on messages from server(Other clients in this case)
        Thread trd = new Thread(listen);
        trd.start();
        //------------------------------            
        while (true) {   

            try {
                String sendMessage = keyboard.nextLine();
                OUT.writeUTF(sendMessage);                    
                OUT.flush();
            } catch (Exception e) {
                System.err.println("Could not send message to server. " + e);
            }
        }           
    } catch (IOException e) {
        System.err.println("Couldnt establish a connection: " + e);
    }        
}
//------------------------------------------------------------    

//CLASS FOR HANDLEING INPUT. We create a class for input on a new thread
//This is cause we don't want it to block other processes.
//----------------------------------------------------------------    
class ListenforMessages implements Runnable{

    Socket mySocket;
    DataInputStream IN;
    public ListenforMessages(Socket X) throws IOException {
        this.mySocket = X;
    }

    @Override
    public void run() {
        try {
            IN = new DataInputStream(mySocket.getInputStream());
            while (true) {                    
                System.out.println(IN.readUTF());   
            }
        } catch (Exception e) {
            System.err.println("Couldn't fetch message from server.Error: " + e);                
        }            
    }

}
}

Answer

Minty Fresh picture Minty Fresh · Mar 12, 2015

There's a couple of solutions to this problem, but a simple one would to be have the client try to reconnect (open a new connection to the server) at set intervals. For example, you could try something like this to have your client try to reconnect once every 3 minutes:

while(true) {
    try {
        clientSocket = new Socket("localhost", portnr);
        break; // We connected! Exit the loop.
    } catch(IOException e) {
        // Reconnect failed, wait.
        try {
            TimeUnit.MINUTES.sleep(3);
        } catch(InterruptedException ie) {
            // Interrupted.
        }
    }
}

This way, the client will try to connect, and if it fails, wait for 3 minutes before trying again.