2013-08-30 31 views
9

tôi có mã đơn giản này cho một máy chủ WebSocket:python cơn lốc xoáy gửi thông điệp tới tất cả các kết nối

import tornado.httpserver 
import tornado.websocket 
import tornado.ioloop 
import tornado.web 
import time 

class WSHandler(tornado.websocket.WebSocketHandler): 

    def open(self): 
    print 'New connection was opened' 
    self.write_message("Conn!") 

    def on_message(self, message): 
    print 'Got :', message 
    self.write_message("Received: " + message) 


    def on_close(self): 
    print 'Conn closed...' 


application = tornado.web.Application([ 
    (r'/ws', WSHandler), 
]) 

if __name__ == "__main__": 
    http_server = tornado.httpserver.HTTPServer(application) 
    http_server.listen(65) 
    tornado.ioloop.IOLoop.instance().start() 

Tôi muốn để có thể gửi một thông điệp tới tất cả khách hàng kết nối, nhưng tôi không biết, và tôi dường như không tìm thấy ở đâu cả. Một chút giúp đỡ xin vui lòng? Cảm ơn

Trả lời

10

Lúc đầu, bạn nên bắt đầu quản lý các kết nối đến thủ công, đó là nguyên nhân gây ra lốc xoáy không làm điều đó từ hộp. Như thực hiện ngây thơ bạn có thể làm như thế này:

class WSHandler(tornado.websocket.WebSocketHandler): 
    connections = set() 

    def open(self): 
    self.connections.add(self) 
    print 'New connection was opened' 
    self.write_message("Conn!") 

    def on_message(self, message): 
    print 'Got :', message 
    self.write_message("Received: " + message) 


    def on_close(self): 
    self.connections.remove(self) 
    print 'Conn closed...' 

vì vậy nếu bạn cần cùng thông điệp tới tất cả các kết nối, bạn có thể làm điều đó:

[con.write_message('Hi!') for con in connections] 
+0

đừng quên rằng builtins không threadsafe – deathangel908

+3

Tôi đã gặp phải lỗi với mã này. Điều chỉnh là: '[con.write_message ('Hi!') Cho con trong self.connections]' – James

Các vấn đề liên quan