I want to verify the connection status before realize my operations (read/write).
Is there a way to make an isConnect() method?
I saw this, but it seems "ugly".
I tested is_open() function also, but doesn't have the expected behavior.
Thanks
you can send a dummy byte on a socket and see if it will return an error.
TCP promises to watch for dropped packets -- retrying as appropriate -- to give you a reliable connection, for some definition of reliable. Of course TCP can't handle cases where the server crashes, or your Ethernet cable falls out or something similar occurs. Additionally, knowing that your TCP connection is up doesn't necessarily mean that a protocol that will go over the TCP connection is ready (eg., your HTTP webserver or your FTP server may be in some broken state).
If you know the protocol being sent over TCP then there is probably a way in that protocol to tell you if things are in good shape (for HTTP it would be a HEAD request)
Just always keep an outstanding async_read, when the connection is severed it will error.
And since like Max mentioned, TCP is meant to be robust in the face of a harsh network, it will only detect a severed connection when the remote end sends a FIN packet to close the connection. To work around this problem take a look at using asio::tcp::socket::keep_alive to enable TCP keep-alive. You can also implement a keep-alive at the application layer like discussed in Andrei's answer.
If you don't want to use async_reads then when you enable keep-alives on the socket is_open() should more accurately detect a severed connection.