Tornado - 通过 websockets 同时收听多个客户端

Tornado - Listen to multiple clients simultaneously over websockets

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

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

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

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)