0

I've implemented a server which accepts requests and after some process the client connects to my server.
The server continuously sends data to client, but if the client lose the network connection (e.g. on my mobile I've disabled the internet access without exiting from the client program), then the server is still writing to the nothing.
I've attached my shortened version of my code logic. Monitoring the input data could be a good idea, but I have some cases when I don't have to wait for any input.

class CustomRequestHandler(BaseHTTPRequestHandler):
    def __init__(self, request, client_address, server):
        BaseHTTPRequestHandler.__init__(self, request, client_address, server)

    def do_GET(self):
        try:
            readable, writable, exceptional = select.select([self.rfile], [self.wfile], [self.rfile, self.wfile], 0)
            for s in readable:
                print (s.readline())
            for s in writable: # 
                s.write(b"Data")
        except Exception as e:
            print(e)
    
    def finish(self, *args, **kw):
        print ("Do finish")

class CustomServer(socketserver.ThreadingMixIn, HTTPServer):
    pass


def start_server():

    httpd = CustomServer((HOST, PORT), CustomRequestHandler)

    try:
        httpd.allow_reuse_address = True
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()


if __name__ == '__main__':
    start_server()

After a while writable became an empty list, but how could I detect if on the client side a network lost occurred? How could I catch the network error?

bummm26
  • 159
  • 3
  • 17

1 Answers1

-1

Your socket is not closed when you cut the network connection. The sender will only get informed when the OS decides that the socket is timed out. This usually takes 30s+.

If on the other hand the receiver program is closed properly, the sender will get notified within milliseconds.

These left open but actually lost connections are a major problem in network programming. There are mitigations but there is no universal ultimate solution to it.

Klaus D.
  • 13,874
  • 5
  • 41
  • 48