如何重新打开套接字连接?

时间:2015-02-12 13:42:47

标签: java sockets connection client server

如果重新打开客户端的套接字连接,如果服务器已停止然后再次运行?

P.S。也许没有必要查看所有代码,只需查看"等待"循环在客户端代码中。

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

1 个答案:

答案 0 :(得分:3)

如果套接字关闭连接客户端应该在读/写操作上获得异常。如果客户端想要重新建立连接,请执行它。你捕获块应该像在代码片段的开头一样创建新的套接字。

如下所示:

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
    }
}