Mojtaba Kamyabi
Mojtaba Kamyabi

Reputation: 3600

how to set connection timeout in tornado?

In my Tornado app in some situation some clients disconnect from server but my current code doesn't detect that client is disconnect from server. I currently use ping to find out if client is disconnected. here is my ping pong code:

from threading import Timer
class SocketHandler(websocket.WebSocketHandler):
    def __init__(self, application, request, **kwargs):
        # some code here
        Timer(5.0, self.do_ping).start()
    def do_ping(self):
        try:
            self.ping_counter += 1
            self.ping("")
            if self.ping_counter > 2:
                self.close()
            Timer(60, self.do_ping).start()
        except WebSocketClosedError:
            pass

    def on_pong(self, data):
        self.ping_counter = 0

now I want to set SO_RCVTIMEO in tornado instead of using ping pong method. something like this :
sock.setsockopt(socket.SO_RCVTIMEO)
Is it possible to set SO_RCVTIMEO in Tornado for close clients from server after specific time out ?

Upvotes: 1

Views: 1724

Answers (1)

Ben Darnell
Ben Darnell

Reputation: 22134

SO_RCVTIMEO does not do anything in an asynchronous framework like Tornado. You probably want to wrap your reads in tornado.gen.with_timeout. You'll still need to use pings to test the connection and make sure it is still working; if the connection is idle there are few guarantees about how long it will take for the system to notice. (TCP keepalives are a possibility, but these are not configurable on all platforms and generally use very long timeouts).

Upvotes: 1

Related Questions