tags:

views:

83

answers:

2

I know Twisted can do this well but what about just plain socket?

How'd you tell if you randomly lost your connection in socket? Like, If my internet was to go out of a second and come back on.

A: 

If the internet comes and goes momentarily, you might not actually lose the TCP session. If you do, the socket API will throw some kind of exception, usually socket.timeout.

Marcelo Cantos
I don't think it gives off any exception really. It just sits there and does nothing.
Dave Dixon
Ah yes, you have to call `socket.settimeout()`. I'm not sure how you would distinguish between a long pause in transmission and an actual outage. Sorry.
Marcelo Cantos
+1  A: 

I'm assuming you're talking about TCP.

If your internet connection is out for a second, you might not lose the TCP connection at all, it'll just retransmit and resume operation.

There's ofcourse 100's of other reasons you could lose the connection(e.g. a NAT gateway inbetween decided to throw out the connection silently. The other end gets hit by a nuke. Your router burns up. The guy at the other end yanks out his network cable, etc. etc.)

Here's what you should do if you need to detect dead peers/closed sockets etc.:

  • Read from the socket or in any other way wait for events of incoming data on it. This allows you to detect when the connection was gracefully closed, or an error occured on it (reading on it returns 0 or -1) - atleast if the other end is still able to send a TCP FIN/RST or ICMP packet to your host.

  • Write to the socket - e.g. send some heartbeats every N seconds. Just reading from the socket won't detect the problem when the other end fails silently. If that PC goes offline, it can obviously not tell you that it did - so you'll have to send it something and see if it responds.

  • If you don't want to write heartbeats every N seconds, you can atleast turn on TCP keepalive - and you'll eventually get notified if the peer is dead. You still have to read from the socket, and the keepalive are usually sent every 2 hours by default. That's still better than keeping dead sockets around for months though.

nos