如何检测远端插座关闭?

时间:2020-03-06 14:54:18  来源:igfitidea点击:

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

解决方案

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

启动服务器,启动客户端。我们会看到它打印了两次" connected:true",即使套接字第二次关闭也是如此。

真正找出答案的唯一方法是在关联的Input / OutputStreams上读取(我们将获得-1作为返回值)或者写入(将抛出IOException(破损的管道))。

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

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