HandlerWebsockets
可以正常工作,并且只是使用messageToSockets(msg)
时的当前发送的回复。但是,两种尝试都无法从Web应用程序的协同程序向WebSocket发送消息的方法。这些尝试似乎阻止了一切……
class webApplication(tornado.web.Application):
def __init__(self):
handlers = [
(r'/', HandlerIndexPage),
(r'/websocket', HandlerWebSocket, dict(msg='start')),
]
settings = {
'template_path': 'templates'
}
tornado.web.Application.__init__(self, handlers, **settings)
@gen.coroutine
def generateMessageToSockets(self):
while True:
msg = str(randint(0, 100))
print ('new messageToCon: ', msg)
yield [con.write_message(msg) for con in HandlerWebSocket.connections]
yield gen.sleep(1.0)
if __name__ == '__main__':
ws_app = webApplication()
server = tornado.httpserver.HTTPServer(ws_app)
port = 9090
print('Listening on port:' + str(port))
server.listen(port)
IOLoop.current().spawn_callback(webApplication.generateMessageToSockets)
IOLoop.current().set_blocking_log_threshold(0.5)
IOLoop.instance().start()
此处是WebSockets处理程序
class HandlerWebSocket(tornado.websocket.WebSocketHandler):
connections = set()
def initialize(self, msg):
print('HWS:' + msg)
def messageToSockets(self, msg):
print ('return message: ', msg)
[con.write_message(msg) for con in self.connections]
def open(self):
self.connections.add(self)
print ('new connection was opened')
pass
def on_message(self, message):
print ('from WebSocket: ', message)
self.messageToSockets(message)
def on_close(self):
self.connections.remove(self)
print ('connection closed')
pass
我在示例,此处的问题,文档等方面有些失落。因此,非常感谢如何正确启动连续调用websocket例程的任何提示
答案 0 :(得分:1)
generateMessageToSockets
将无休止地循环,以尽可能快的速度生成消息,而无需等待这些消息被发送。由于它首先启动并且永不屈服,因此HTTPServer实际上将永远无法接受连接。
如果您真的想尽可能快地发送消息,则不阻塞的最小解决方案是
yield [con.write_message(msg) for con in HandlerWebSocket.connections]
yield gen.moment
但是最好使用gen.sleep
定期发送消息,而不是“尽可能快”发送消息。
答案 1 :(得分:1)
不幸的是,所有gen.routines尝试都不适用于我。回到主题
def generateMessageToSockets():
while True:
msg = str(randint(0, 100))
print ('new messageToCon: ', msg)
[con.write_message(msg) for con in HandlerWebSocket.connections]
sleep(1.0)
class WebApplication(tornado.web.Application):
def __init__(self):
handlers = [
(r'/', HandlerIndexPage),
(r'/websocket', HandlerWebSocket, dict(msg='start')),
]
settings = {
'template_path': 'templates'
}
tornado.web.Application.__init__(self, handlers, **settings)
if __name__ == '__main__':
tGenarate = threading.Thread(target=generateMessageToSockets)
tGenarate.start()
ws_app = WebApplication()
server = tornado.httpserver.HTTPServer(ws_app)
port = 9090
print('Listening on port:' + str(port))
server.listen(port)
ioloop.IOLoop.instance().start()
有效