问题描述
你如何检测 Socket#close()
是否在远程端的套接字上被调用?
How do you detect if Socket#close()
has been called on a socket on the remote side?
推荐答案
isConnected
方法无济于事,即使远程端关闭,它也会返回 true
插座.试试这个:
The isConnected
method won't help, it will return true
even if the remote side has closed the socket. Try this:
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",即使套接字第二次关闭.
Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.
真正找出答案的唯一方法是在关联的 Input/OutputStreams 上读取(您将获得 -1 作为返回值)或写入(将抛出 IOException
(管道损坏)).
The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException
(broken pipe) will be thrown) on the associated Input/OutputStreams.
这篇关于如何检测远程端套接字关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!