如何检查 Socket 当前是否已在 Java 中连接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1390024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check if a Socket is currently connected in Java?
提问by Supertux
I'm trying to find out whether a Java TCP Socket is currentlyconnected, the following just seems to tell me whether the socket has been connected at some point - not whether it is currently still connected.
我试图找出当前是否连接了 Java TCP 套接字,以下内容似乎只是告诉我套接字是否已在某个时候连接 - 而不是它当前是否仍处于连接状态。
socket.isConnected();
Any help appreciated, thanks.
任何帮助表示赞赏,谢谢。
回答by Jason Nichols
Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.
假设您对协议有一定程度的控制,我非常喜欢发送心跳来验证连接是否处于活动状态。它已被证明是最有效的防故障方法,并且通常会在连接中断时为您提供最快的通知。
TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.
TCP keepalive 可以工作,但是如果远程主机突然断电怎么办?TCP 可能需要很长时间才能超时。另一方面,如果您的应用程序中的逻辑期望每 x 秒收到一次心跳回复,那么第一次您没有得到它们时,您就知道连接不再有效,无论是由于网络还是远程服务器问题.
See Do I need to heartbeat to keep a TCP connection open?for more discussion.
请参阅我是否需要心跳才能保持 TCP 连接打开?更多讨论。
回答by Sumit Singh
socket.isConnected()
returns always true once the client connects (and even after the disconnect) weird !!socket.getInputStream().read()
- makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
returns -1
if the client disconnected
socket.getInetAddress().isReachable(int timeout)
: From isReachable(int timeout)Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.
socket.isConnected()
一旦客户端连接(甚至在断开连接之后),它总是返回 true 很奇怪!socket.getInputStream().read()
- 只要客户端连接,线程就会等待输入,因此使您的程序不执行任何操作 - 除非您获得一些输入
returns -1
如果客户端断开连接
socket.getInetAddress().isReachable(int timeout)
: 从isReachable(int timeout)测试该地址是否可达。实现会尽最大努力尝试访问主机,但防火墙和服务器配置可能会阻止请求,导致无法访问状态,而某些特定端口可能可以访问。如果可以获得特权,典型的实现将使用 ICMP ECHO REQUEST,否则它将尝试在目标主机的端口 7(Echo)上建立 TCP 连接。