python tornado发送消息给所有连接

时间:2013-08-30 11:31:11

标签: python tornado

我有一个websocket服务器的简单代码:

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()

我希望能够向所有连接的客户端发送消息,但我不知道,我似乎无法在任何地方找到它。请帮帮忙吗?感谢

1 个答案:

答案 0 :(得分:11)

首先你应该开始管理传入的连接,这是因为龙卷风不会从框中做到这一点。作为天真的实现,你可以这样做:

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...'

因此,如果您需要向所有连接发送相同的消息,则可以执行此操作:

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