【发布时间】:2020-02-04 13:46:03
【问题描述】:
我正在运行一个 tornado 应用程序,但我意识到每次与套接字建立新连接时,它都会创建一个新的服务器实例,而不是将新连接添加到 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 与 tornado.ioloop.IOLoop.instance(我正在使用)的相关信息,但文档说 .instance 只是 .current 的别名。
【问题讨论】:
标签: python sockets websocket tornado python-asyncio