Frage

I want to add a timeout to individual connections within my request handler for a server using the SocketServer module.

Let me start by saying this is the first time I'm attempting to do network programming using Python. I've sub-classed SocketServer.BaseRequestHandler and SocketServer.ThreadingTCPServer & SocketServer.TCPServer and managed to create two classes with some basic threaded TCP functionality.

However I would like my incoming connections to time-out. Trying to override any of the built in SocketServer time-out values and methods does not work, as the documentation says this works only with forking server. I have managed to create a timer thread that fires after X seconds, but due to the nature of the blocking recv call within the Handler thread, this is of no use, as I would be forced to kill it, and this is something I really want to avoid.

So it is my understanding that I need an asyncore implementation, where I get notified and read certain amount of data. In the event that no data is sent over a period of 5 seconds lets say, I want to close that connection (I know how to cleanly do that). I have found a few examples of using asyncore with sockets, but none using SocketServer. So, how can I implement asyncore & threadingTCPserver ? Is it possible? Has anyone done it?

War es hilfreich?

Lösung

You can also set a timeout on the recv call, like this:

sock.settimeout(1.0)

Since you use SocketServer, you will have to find the underlying socket somewhere in the SocketServer. Please note that SocketServer will create the socket for you, so there is no need to do that yourself.

You will probably have defined a RequestHandler to go with your SocketServer. It should look something like this:

class RequestHandler(SocketServer.BaseRequestHandler):
    def setup(self):
         # the socket is called request in the request handler
         self.request.settimeout(1.0)

    def handle(self):
         while True:
             try: 
                 data = self.request.recv(1024)
                 if not data:
                      break # connection is closed
                 else:
                      pass  # do your thing
             except socket.timeout:
                 pass # handle timeout
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top