【问题标题】:python tornado send message to all connectionspython tornado 向所有连接发送消息
【发布时间】:2013-08-30 11:31: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()

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

【问题讨论】:

    标签: python tornado


    【解决方案1】:

    首先,您应该开始手动管理传入连接,这是因为龙卷风不会从框中执行此操作。作为幼稚的实现,您可以这样做:

    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]
    

    【讨论】:

    • 我一直遇到此代码错误。更正为:[con.write_message('Hi!') for con in self.connections]
    • 我让我的客户端不断地在一个循环中监听服务器,正如这里提到的 tornadoweb.org/en/stable/websocket.html#client-side-support。我无法使用上述使用列表的过程让多个客户端实例连接到服务器。第二个客户端总是等待第一个客户端进程结束,然后我才能从服务器读取消息。有什么办法吗?我使用与上面完全相同的模型来允许多个连接..
    • @Denis,而不是持有一组连接,并使用更多内存 - Tornado 不是已经在内部保存了这样的数据结构吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    相关资源
    最近更新 更多