如何检测远程侧socketsclosures?

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

isConnected方法将不起作用,即使远程端closures了套接字,它也会返回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()); } } 

启动服务器,启动客户端。 即使套接字第二次closures,您将看到它会打印“connected:true”两次。

要真正发现的唯一方法是通过读取(您将得到-1作为返回值)或在相关的Input / OutputStreams上写入( IOException (断开的pipe道))。

由于答案偏离,我决定testing这个并发布结果 – 包括testing的例子。

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

服务器:

 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 ... } 
  • 一旦客户端连接(甚至在断开连接之后),clientSocket.isConnected()将始终返回true!
  • 的getInputStream()。阅读()
    • 只要客户端连接,就让线程等待input,从而使你的程序不做任何事情 – 除非你得到一些input
    • 如果客户端断开,则返回-1
  • out.checkError()是一旦客户端断开连接,所以我推荐这个

写入客户端套接字时,您还可以检查套接字输出stream错误。

 out.println(output); if(out.checkError()) { throw new Exception("Error transmitting data."); } 

如果远程系统断开/closures了连接,Socket.Available方法将立即抛出一个SocketException。