如何在 Tornado Websocket 中的特定时间后自动关闭连接服务器端

How to automatically close connection serverside after a certain time in Tornado Websocket

我有一个 Tornado Websocket 服务器,它有一个开放连接字典:

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self, *args):
        self.id = self.generate_id()
        self.stream.set_nodelay(True)

        # ... DO STUFF ...

        clients[self.id] = {"id": self.id, "time":datetime.now(), "object": self}
        self.write_message("Connection SUCCESSFUL! Thanks for connecting! Your connection ID is: %d :)" % self.id)
        print datetime.now()
        print "New connection. ID: %d" % self.id
        print "Total number of open connections: %d" % len(clients)

    def on_close(self):
        print datetime.now()
        print "Closing connection %d." % self.id 
        if self.id in clients:
            del clients[self.id]
        print "Number of open connections: %d" % len(clients)

我想自动关闭所有超过一小时的连接。所以像这样:

for client in clients.values():
    if (datetime.now() - client["time"])>timedelta(minutes=60):
        client["object"].close()

但我不知道我应该把这个检查放在哪里并关闭旧连接。

请参阅this answer进一步说明

import tornado
import datetime
class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self, *args):
        self.id = self.generate_id()
        self.stream.set_nodelay(True)
        self.timeout = tornado.ioloop.IOLoop.current().add_timeout(
            datetime.timedelta(minutes=60), self.explicit_close)

        # ... DO STUFF ...

        clients[self.id] = {"id": self.id, "time":datetime.now(), "object": self}
        self.write_message("Connection SUCCESSFUL! Thanks for connecting! Your connection ID is: %d :)" % self.id)
        print datetime.now()
        print "New connection. ID: %d" % self.id
        print "Total number of open connections: %d" % len(clients)

    def on_close(self):
        print datetime.now()
        print "Closing connection %d." % self.id 
        if self.id in clients:
            del clients[self.id]
        print "Number of open connections: %d" % len(clients)

    def explicit_close(self):
        self.close() # you wont even have to iterate over the clients.

Follow the IOLoop of tornado and reference question it will be easy to understand.