如何检测远程侧插座关闭? [英] How to detect a remote side socket close?
本文介绍了如何检测远程侧插座关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检测是否已在远程端的套接字上调用套接字#close()
?
推荐答案
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.
真正找到答案的唯一方法是阅读(你将获得-1作为返回值)或在相关的Input / OutputStreams上写(将抛出 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.
这篇关于如何检测远程侧插座关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文