Python Forum

Full Version: Set request timeout for socketserver
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm implementing simple server which should accept connection from client, receive and send data from some time (e.g. couple of minutes) then close connection and accept another connection.

I defined handler and server classes as follows
import time
import socketserver


class MyHandler(socketserver.BaseRequestHandler):

    def handle(self):
        print('{} - Incoming connection from {}'.format(time.strftime('%d.%m.%Y %H:%M:%S', time.localtime()), self.client_address))

        data = self.request.recv(8192)
        self.request.sendall(data)


class MyServer(socketserver.TCPServer):
    timeout = 3

    def __init__(self, serverAddress, RequestHandlerClass):
        socketserver.TCPServer.__init__(self, serverAddress, RequestHandlerClass)

    def handle_timeout(self):
        print('{} - Timeout'.format(time.strftime('%d.%m.%Y %H:%M:%S', time.localtime())))


if __name__ == '__main__':
    server = MyServer(('localhost', 9999), MyHandler)
    print("Server started.")

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.shutdown()
        server.server_close()
        print("Server stopped.")
After starting server, I connected to it and waited for some time. I expected that after 3 second of inactivity connection will be closed, but it remains active. What I'm doing wrong, how to accept serve each connection only for predefined time?

Thanks