龙卷风在事件中发送消息 [英] Tornado send message on event
问题描述
我正在用 Python 创建一个程序,该程序以未知的时间间隔读取数据流.该程序还通过 websockets 发送这些数据.程序是服务器,它将接收到的数据发送给客户端.
Im creating a program in Python that reads a stream of data on an unknown interval. This program also sends this data through websockets. The program is the server and it sends the received data to the clients.
这是现在服务器的代码:
This is the code of the server now:
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def initialize(self):
print 'Websocket opened'
def open(self):
print 'New connection'
self.write_message('Test from server')
def on_close(self):
print 'Connection closed'
def test(self):
self.write_message("scheduled!")
def make_app():
return tornado.web.Application([
(r'/ws', WebSocketHandler),
])
if __name__ == '__main__':
application = make_app()
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
但我希望能够在这个循环中使用 write_message
:
But I want to be able to use write_message
in this loop:
def read_function():
while True:
time.sleep(10) # a while loop to simulate the reading
print 'read serial'
str = 'string to send'
# send message here to the clients
我该怎么做?
使用连接的两个线程都会有问题吗?它似乎适用于 1 个连接.
will there be a problem with both threads using connections? It seems like it works with 1 connection.
def read_function():
while True:
time.sleep(5) # a while loop to simulate the reading
print 'read serial'
str = 'string to send'
[client.write_message(str) for client in connections]
if __name__ == '__main__':
thread = Thread(target = read_function)
application = make_app()
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
thread.start()
tornado.ioloop.IOLoop.instance().start()
thread.join()
推荐答案
在 WebsocketHandler 之外使用 connections = set()
并在打开连接时使用 connections.add(self)
.不要忘记在关闭时使用 connections.remove(self)
删除它们.
Use connections = set()
outside the WebsocketHandler and add every client on opening a connection with connections.add(self)
. Do not forget to remove them on closing with connections.remove(self)
.
现在,您可以通过以下方式从 websocket 线程中访问 write_message
:[client.write_message('#your_message') for client in connections]
Now, you are able to access write_message
out of the websocket thread through: [client.write_message('#your_message') for client in connections]
这篇关于龙卷风在事件中发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!