【问题标题】:How to reopen socket connection?如何重新打开套接字连接?
【发布时间】:2015-04-13 06:41:38
【问题描述】:

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

附:可能不需要查看所有代码,只需查看Client代码中的“等待”循环即可。

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

【问题讨论】:

  • 如果连接已关闭,那么我会说创建新连接的方式与往常一样。
  • 即使在创建新套接字后它仍然是关闭的 (( socket = new Socket(socket.getInetAddress(), socket.getPort());
  • new Socket(socket.getInetAddress(), socket.getPort()) 不是“你总是这样做的方式”。请参阅 AlexR 的回答以了解我的意思。

标签: java sockets connection client server


【解决方案1】:

如果套接字关闭连接客户端应该在读/写操作时出现异常。如果客户想重新建立连接,只需实现它。您的 catch 块应该完全按照您在代码 sn-p 开头所做的那样创建新套接字。

类似于以下内容:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多