如何检测远程侧插座关闭?

Kev*_*ong 82 java sockets networking tcp

如何检测是否Socket#close()已在远程端的套接字上调用?

WMR*_*WMR 63

isConnected方法无济于事,true即使远程端已关闭套接字,它也会返回.试试这个:

public class MyServer {
    public static final int PORT = 12345;
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
        Socket s = ss.accept();
        Thread.sleep(5000);
        ss.close();
        s.close();
    }
}

public class MyClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
        System.out.println(" connected: " + s.isConnected());
        Thread.sleep(10000);
        System.out.println(" connected: " + s.isConnected());
    }
}
Run Code Online (Sandbox Code Playgroud)

启动服务器,启动客户端.您将看到它打印"connected:true"两次,即使套接字第二次关闭.

真正找到的唯一方法是通过读取(你将得到-1作为返回值)或IOException在相关的Input/OutputStreams上写入(一个(破坏的管道)).

  • 为什么会有这么多的赞成:/它甚至没有回答问题,它只是在解释_什么不会起作用_... (9认同)
  • 找出的唯一方法是写.从突然关闭的套接字读取可能并不总是返回-1.http://stackoverflow.com/a/6404085/372643 (4认同)

Tho*_*ues 26

由于答案有所不同,我决定对此进行测试并发布结果 - 包括测试示例.

这里的服务器只是将数据写入客户端,并且不期望任何输入.

服务器:

ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
  out.println("output");
  if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
  System.out.println(clientSocket.isConnected());
  System.out.println(clientSocket.getInputStream().read());
        // thread sleep ...
  // break condition , close sockets and the like ...
}
Run Code Online (Sandbox Code Playgroud)
  • clientSocket.isConnected()一旦客户端连接(甚至断开连接后)就会返回true!
  • 的getInputStream().阅读()
    • 只要客户端连接,线程就会等待输入,从而使你的程序不做任何事情 - 除非你得到一些输入
    • 如果客户端断开连接则返回-1
  • 一旦客户端断开连接,out.checkError()就为true,所以我推荐这个

  • 一旦在写入时检测到错误,checkError()就为真,并且不久.一旦客户端断开连接,它肯定不会成为现实.-1 (24认同)

小智 13

您还可以在写入客户端套接字时检查套接字输出流错误.

out.println(output);
if(out.checkError())
{
    throw new Exception("Error transmitting data.");
}
Run Code Online (Sandbox Code Playgroud)

  • 你*可以*,但你不一定会立即得到它。 (2认同)