【问题标题】:Tornado - Listen to multiple clients simultaneously over websocketsTornado - 通过 websockets 同时监听多个客户端
【发布时间】:2015-08-25 11:11:00
【问题描述】:

我想使用 Tornado 在 Python 中创建 websocket 服务器。这是 API:http://tornado.readthedocs.org/en/latest/websocket.html

在 API 中,我没有看到为客户端获取句柄的选项。如何同时处理多个客户端连接?
例如on_message(self, message) 方法直接给出消息。不包含已连接客户端的任何句柄。
我想接收客户端请求,进行一些处理(这可能需要很长时间),然后回复客户端。我正在寻找可用于稍后回复的客户端句柄。

【问题讨论】:

    标签: python python-2.7 tornado


    【解决方案1】:

    据我了解,您想要这样的东西:

    class MyWebSocketHandler(tornado.websocket.WebSocketHandler):
        # other methods
        def on_message(self, message):
            # do some stuff with the message that takes a long time
            self.write_message(response)
    

    每个 websocket 连接都有自己的子类 WebSocketHandler 对象。

    您甚至可以保存连接并在其他地方使用它:

    ws_clients = []
    
    class MyWebSocketHandler(tornado.websocket.WebSocketHandler):
        # other methods
        def open(self):
            if self not in ws_clients:
                ws_clients.append(self)
    
        def on_close(self):
            if self in ws_clients:
                ws_clients.remove(self)
    
    def send_message_to_all(self, message):
        for c in ws_clients:
            c.write_message(message)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      • 2015-05-06
      相关资源
      最近更新 更多