[英]How to detect the server disconnection to the client immediately in Java(Android) socket communication
I am working on socket programming. 我正在进行套接字编程。 Is there any way to detect the server disconnection to the client immediately.
有什么方法可以立即检测到服务器与客户端的断开连接。
I used socket.isConnected , isBound methods but I did't get good results. 我使用了socket.isConnected,isBound方法,但是没有得到很好的结果。
I tried to read the data from the stream continuously to check but it blocks that if data is not available or return from the server and I don't want to write garbage data to send each time to check the connection with the server. 我试图从流中连续读取数据以进行检查,但是它阻止了数据是否不可用或是否从服务器返回,并且我不想编写垃圾数据来每次发送以检查与服务器的连接。
Please suggest any suggestions. 请提出任何建议。
It depends on which socket type you're using. 这取决于您使用的套接字类型。 Even then it is unavoidable to implement a keep-alive mechanism for your specific purpose.
即使这样,也不可避免地要为您的特定目的实现保持活动的机制。
The default TCP keep-alive mechanism checks every 2 hours (!) if the connection still exists. 默认的TCP保持活动机制每2小时(!)检查一次连接是否仍然存在。 This default value can be changed but it may not work.
可以更改此默认值,但它可能不起作用。 See:
看到:
Does a TCP socket connection have a "keep alive"? TCP套接字连接是否具有“保持活动”状态?
UDP on the other hand is stateless; 另一方面,UDP是无状态的。 there is no connection.
没有连接。 The context in which socket.isConnected() should be interpreted is whether it's bound to a local port.
应该解释socket.isConnected()的上下文是它是否绑定到本地端口。
For UDP it is an absolute requirement to send ping/pongs back and forth to determine connectivity. 对于UDP,绝对要求来回发送ping / pongs以确定连接性。
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.