2016-11-17 71 views
0

我在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() 
+0

您可能還需要從集合中刪除連接,當他們得到斷開。 –

回答

1

使用connections = set()的WebsocketHandler外,並添加每個客戶端上打開與connections.add(self)的連接。不要忘記在關閉connections.remove(self)時將其刪除。

現在,您可以通過訪問write_message出的WebSocket線程:[client.write_message('#your_message') for client in connections]

+0

謝謝!但是,在另一個線程中運行read_function的最佳方式是什麼?我應該創建一個與標準線程庫分開的線程?謝謝 –

+0

這個函數是如何調用的? – Kjub

+0

我只是在主函數中調用它。它應該是一個循環檢查輸入,並在輸入它時發送消息。但是我現在只需將它放在另一個線程上就可以工作。我只是想知道如果它的良好做法。我將在編輯中顯示主要內容。 –