11

我有一个 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()

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

4

1 回答 1

12

首先,您应该开始手动管理传入连接,这是因为龙卷风不会从盒子里做到这一点。作为幼稚的实现,您可以这样做:

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]
于 2013-08-30T12:08:58.733 回答