Socket Lose connection
I am assuming you are talking about TCP.
If your internet connection is down for a second, you may not lose your TCP connection at all, it will simply retry the transmission and resume.
At the same time, for 100 other reasons you can lose the connection (for example, the NAT gateway in the meantime decided to disconnect the connection quietly, and the other end falls into the kernel discharge. Your router is on fire. The guy on the other end is pulling his network cable, etc. ).
Here's what you should do if you need to detect dead peers / closed sockets, etc .:
-
Read from socket or otherwise wait for incoming data events to appear on it. This allows you to detect when a connection was gracefully closed, or an error occurred on it (reading on it returns 0 or -1) - at least if the other end can still send a TCP FIN / RST or ICMP packet to your host.
-
Writing to a socket - for example. send several heartbeats every N seconds. A simple read from the socket will show no problem when the other end fails. If that computer is off, it obviously won't tell you that it did - so you'll have to send something and see if it responds.
-
If you don't want to write heartbeats every N seconds, you can still enable TCP keepalive - and you will eventually receive a notification if the peer is dead. You will still have to read from the socket, and the keepalive is usually sent every 2 hours by default. It's even better than keeping dead sockets for months, though.
a source to share