如何一次向龙卷风套接字客户端广播消息?

How to broadcast a message to tornado socket clients all at once?

我正在 运行 开发一个龙卷风应用程序,但我意识到每次与套接字建立新连接时,它都会创建一个新的服务器实例,而不是将新连接添加到 self.connections.由于这种行为,我无法同时向所有连接广播消息。如何使用现有实例制作应用 运行?

import asyncio
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.wsgi
import time


class EchoWebSocket(tornado.websocket.WebSocketHandler):

    def initialize(self, tornado_output_queue):
        self.connections = set()

    def open(self):
        print("WebSocket opened")
        self.connections.add(self)

    def on_message(self, message):
        for client in self.connections:
            await client.write_message(str(time.time()))

    def on_close(self):
        print("WebSocket closed")

    def check_origin(self, origin):
        return True


def make_app():
    "initializes the web server"
    return tornado.web.Application([
        (r"/websocket", EchoWebSocket)
    ])


if __name__ == "__main__":
    webapp = make_app()
    application = tornado.wsgi.WSGIContainer(webapp)
    webapp.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

我读过 tornado.ioloop.IOLoop.current Vs tornado.ioloop.IOLoop.instance(我正在使用),但文档说 .instance 只是 .current.[=15 的别名=]

Tornado 为每个连接创建一个新的处理程序实例。要跟踪所有已连接的客户端,您必须在 class:

上创建 connections 对象
class EchoWebSocket(...):
    connections = set()