龙卷风:识别/跟踪websocket的连接?

发布于 2021-01-29 15:07:01

我有一个基本的Tornado websocket测试:

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
        self.write_message("Hello World")

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

    def on_close(self):
      print 'connection closed'


application = tornado.web.Application([
    (r'/ws', WSHandler),
])


if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

我希望能够处理多个连接(似乎已经做到了),而且还能够引用其他连接。我没有一种方法来识别和跟踪单个连接,只是为了能够处理打开连接,接收消息和关闭连接时的事件。

[编辑]
想创建一个dict,其中键是Sec-websocket-key,值是WSHandler对象…。我不确定Sec-websocket-key的可靠性如何。

关注者
0
被浏览
76
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    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'
    

    如果要标识连接(例如按用户),则可能必须通过套接字发送该信息。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看