How to check if a socket connection is live in Boost::asio?

前端 未结 2 480
北荒
北荒 2021-01-17 19:46

I\'m using the Boost::asio to implement a client/server applicaion. The client code below is used to connect to the remote server .

   try
    {
        bo         


        
相关标签:
2条回答
  • 2021-01-17 19:55

    This is a limitation of the underlying socket interface (I think both for Winsock/Bekerly). You could invent a message specifically for this purpose, that the server answers on if it is alive. Else if you get a timeout, means connection is down.

    EDIT: As Joachim pointed out, trying to read the socket might be a better way.

    0 讨论(0)
  • 2021-01-17 19:58

    Due to the limitation of the underlying socket interface, there is no way to implement the function like isConnected to check the TCP connection status at the socket level. I think out a workaround about it.

    In my implementation, I cache a connection status flag (bool m_IsConnected) in my application. This flag is used to designate the connection status. It assumes that if there is no error from socket, the TCP connection is alive.

    The flag will be updated every time when use the socket. If there are errors when send and read data, that means the connection is disconnected. Then change the flag correspondingly. If the TCP connection is idle for a long time. This flag doesn't reflect the actual status of the TCP connection until using the socket. For example, the socket is idle for a long time. It is disconnected due to the poor network. In this case, the m_IsConnected is still true since we don't get any callback regarding the disconnection event. When try to send data through this socket, there will be error. And now we know that the connection is disconnected.

    0 讨论(0)
提交回复
热议问题