Due to the limitations of the underlying socket interface, it is not possible to implement a function such as isConnected to check the status of a TCP connection at the socket level. I think of a workaround.
In my implementation, I cache the connection status flag ( bool m_IsConnected
) in my application. This flag is used to indicate connection status. He assumes that if there is no error in the juice, the TCP connection will be alive.
The flag will be updated every time a socket is used. If there are errors when sending and reading data, this means that the connection is disconnected. Then change the flag accordingly. If the TCP connection is idle for a long time. This flag does not reflect the actual state of the TCP connection before using the socket. For example, a socket has been idle for a long time. It is disconnected due to a bad network. In this case, m_IsConnected is still true, since we are not getting any callback regarding the disconnect event. An attempt will be made to send data through this socket. And now we know that the connection is disconnected.
source share