且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Tornado:识别/跟踪 websockets 的连接?

更新时间:2023-09-18 22:02:16

最简单的方法就是保留一个 WSHandler 实例的列表或字典:

The simplest method is just to keep a list or dict of WSHandler instances:

class WSHandler(tornado.websocket.WebSocketHandler):
    clients = []

    def open(self):
        self.clients.append(self)
        print 'new connection'
        self.write_message("Hello World")

    def on_message(self, message):
        print 'message received %s' % message

    def on_close(self):
        self.clients.remove(self)
        print 'closed connection'

如果您想识别连接,例如对于用户,您可能必须通过套接字发送该信息.

If you want to identify connections, e.g. by user, you'll probably have to send that information over the socket.