简体   繁体   中英

How do we know a StreamSocket's state?

How do I check if a SteamSocket is connected or not?

I have found nothing related or useful in the official docs and slides.

Thanks in advance

after several hours of googling i figured out this is not a problem with Poco . it seems by design C sockets themselves dont know about their own states, and Poco sockets are based on C sockets, so everything just makes sense.

(i havent learned C/C++ basics, i got in programming with Qt directly, whose sockets do provide functions for checking connection states. due to the lack of basic C/C++ knowledge my conclusion above could be wrong )

for blocking sockets : by now the only solution i found is to use StreamSocket::receiveBytes(), it returns 0 if the peer had used shutdown() to close the connection, and throws exceptions if connection lost or something alike.

for non blocking sockets: totally no idea :)

Checking whether a socket is still connected is way harder than it sounds at first. For example, the socket may still be connected from the view of your system, but the other host may have crashed. Or there may be a problem in the network, etc.

Generally, if you'd just like to know whether you haven't yet called close() on the socket, you can do:

bool connected = socket.impl()->initialized();

On the other hand, if you really need to find out whether a connection is still alive, you'll have to send a message to the peer and wait for its response. That's the only reliable way to tell the connection is alive. If you just need to find out whether the peer has closed the socket, try a poll() with short timeout, followed by a receiveBytes() (if poll() has indicated that there's something to read), which will return 0 if the peer has closed the connection. You can also try setting the socket to nonblocking and calling receiveBytes() .

I also recommend having a look a the Unix Socket FAQ .

When writing network code, whether TCP sockets or HTTP, or any other protocol, I highly recommended having a solid knowledge of the specific protocols and mechanisms, and not just use a high-level API and hope for the best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM