我正在用Python创建一个程序,它以未知的间隔读取数据流。这个程序也通过websockets发送这些数据。程序是服务器,它将接收到的数据发送给客户端。
现在是服务器的代码:
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
:
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个连接就可以了。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)
时将它们移除。
write_message
: [client.write_message('#your_message') for client in connections]