我在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()
您可能還需要從集合中刪除連接,當他們得到斷開。 –