Yurii Kyparus
Yurii Kyparus

Reputation: 103

How to reopen socket connection?

How to reopen socket connection of the client, if sever was stopped then ran again?

P.S. Maybe it is not necessary to view all the code, just look through the "wait" loop in the Client code.

Socket socket = new Socket(ipAddress, serverPort);

while (true) 
{
    line = keyboard.readLine();
    try 
    {
       out.writeUTF(line);
       out.flush();
       line = in.readUTF();
    } 
    catch (SocketException e) 
    {
       while (socket.isClosed()) 
       {
           System.out.println("no signal");
           try 
           {
                Thread.sleep(200);
           }
           catch (InterruptedException e1) 
           {
                e1.printStackTrace();
           }

           //Here I need some code for reconnection
         }

    }
    System.out.println(line);
}

Upvotes: 0

Views: 1111

Answers (1)

AlexR
AlexR

Reputation: 115328

If socket closed connection client should get exception on read/write operation. If client wants to re-new the connection, just implement it. You catch block should create new socket exactly as you are doing in the beginning of your code snippet.

Something like the following:

while(true) {
    Socket socket = new Socket(ipAddress, serverPort);
    try {
        while(true) {
           // read/write operations
        }
    } catch (SocketException e) {
       continue; // this will return you to creation of new socket
    }
}

Upvotes: 4

Related Questions