如何检查Socket目前是否以Java连接? [英] How do I check if a Socket is currently connected in Java?

查看:137
本文介绍了如何检查Socket目前是否以Java连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图找出Java TCP Socket是否当前连接,以下似乎只是告诉我套接字是否已经连接 - 而不是它当前是否仍然连接。

I'm trying to find out whether a Java TCP Socket is currently connected, the following just seems to tell me whether the socket has been connected at some point - not whether it is currently still connected.

socket.isConnected();

感谢任何帮助,谢谢。

推荐答案


  • socket.isConnected()一旦客户端连接(甚至在断开连接后),它总是返回true !!

  • socket.getInputStream()。read()


      只要客户端连接,
    • 使线程等待输入,因此使你的程序不做任何事情 - 除非你得到一些输入

    • 返回 - 1 如果客户端已断开连接

      • 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

        • 测试该地址是否可达。尽管尝试到达主机,但是防火墙和服务器配置可以阻止导致无法访问状态的请求,同时可以访问某些特定端口。如果可以获得权限,典型的实现将使用ICMP ECHO REQUEST,否则它将尝试在目标主机的端口7(Echo)上建立TCP连接。

          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目前是否以Java连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆