How to check if socket connection supports in Boost :: asio?

I am using Boost :: asio to implement the client / server application. The client code below is used to connect to a remote server.

try { boost::asio::io_service m_io_service; boost::asio::ip::tcp::socket m_socket(m_io_service); boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 17); m_socket.connect(endpoint); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } 

On the client side, I want to check if the connection is alive. The function " m_socket.is_open(); " does not work. When the server socket is closed, " m_socket.is_open(); " still returns true on the client side. Is there a way to test the connection?

+6
source share
2 answers

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.

+2
source

This is a limitation of the base socket interface (I think for Winsock / Bekerly as well). You can come up with a message specifically for this purpose, to which the server responds if it is alive. If you have a timeout, then the connection is not working.

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

0
source

Source: https://habr.com/ru/post/911915/


All Articles