How to check the connection state of a TCP Server (Socket) with TCP Client in VB.NET

≯℡__Kan透↙ 提交于 2019-12-01 10:53:52

Systems often handle this kind of problem by implementing a 'heartbeat' mechanism where the client periodically sends a 'are you alive' request to the server. Is there any cheap, non-destructive request you can send to the server periodically that would allow you to ensure the socket is actually alive?

This was something I struggled with for quite some time and never really found a catch-all solution. Unfortunately there is not a 100% reliable way, which is why most system implement a 'heartbeat' (as Steve Townsend mentioned).

The closest I could get was something like this (translated from C# by memory):

Public Function IsConnected() as Boolean
    Try
        Return tcpSocket <> Nothing AndAlso Not(tcpSocket.Poll(-1, SelectMode.SelectRead) _
                 AndAlso tcpSocket.Available = 0)
    Catch (ObjectDisposedException)
        Return False
    End Try
End Function

I don't know your setup exactly, but you mention you are connecting to a scale. Perhaps you could try reading the weight from it periodically as a form of 'heartbeat'.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!