2

I'm writing a pair of client/server scripts where it is important to maintain connection as well as detect quickly when the client disconnects. The server normally only sends data, so to test if the client has disconnected normally, I set the socket to timeout mode and check what it returns:

try: # check if client disconnect
    c.settimeout(1)
    if not (c.recv(1024)):
        print("## Socket disconnected! ##")
        c.settimeout(None)
        closeConnection(c)
        return
except Exception as e:
    print(e)
    c.settimeout(None)

This works instantly if I close the client. However, if I disconnect the WiFi on the client machine, the recv on the server doesn't return anything. It just times out like it would if the connection was up but there wasn't anything being sent.

I've tried using send() to send empty messages to the client as a way to poll. When I do this, the operation succeeds and returns 0 regardless of if the client has disconnected.

sddaa
  • 31
  • 1
  • *"... the operation succeeds and returns 0 regardless of if the client has disconnected"* - I've seen this behavior with mobile devices and connection managers. Connection managers pretend a network connection is available even when there is none. Are you seeing the behavior on a desktop, server or mobile device? – jww Apr 14 '19 at 23:39
  • 1
    Possible duplicate of [Detecting TCP Client Disconnect](https://stackoverflow.com/questions/283375/detecting-tcp-client-disconnect) – Nathan Vērzemnieks Apr 15 '19 at 00:51
  • @jww Server is on a Google Cloud virtual machine. I've tested the client on Windows and Mac laptops on my home wifi. Using send() to check for orderly disconnects works fine (calls to it throw an exception) but it only returns 0 if you disconnect the WiFi on the client. – sddaa Apr 15 '19 at 14:25

0 Answers0