如何在龙卷风websocket中向特定客户端发送服务器消息

时间:2017-10-19 11:44:41

标签: python websocket tornado

嘿,我是python的新手,这里是龙卷风中的Websocket服务器代码

PS4="+$(basename $0): "
propagate_options='-d'
set -x

它正常工作并在服务器上接收我的消息(客户端消息),但遗憾的是它没有向我发送其他客户端消息。就像我有这个HTML

import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.template

class MainHandler(tornado.web.RequestHandler):
  def get(self):
    loader = tornado.template.Loader(".")
    self.write(loader.load("index.html").generate())

class WSHandler(tornado.websocket.WebSocketHandler):
  def open(self):
    print 'connection opened...'
    self.write_message("The server says: 'Hello'. Connection was accepted.")

  def on_message(self, message):
    self.write_message("The server says: " + message + " back at you")
    print 'received:', message

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

application = tornado.web.Application([
  (r'/ws', WSHandler),
  (r'/', MainHandler),
  (r"/(.*)", tornado.web.StaticFileHandler, {"path": "./resources"}),
])

if __name__ == "__main__":
  application.listen(9090)
  tornado.ioloop.IOLoop.instance().start()

当我从客户端点击发送按钮(使用上面的html)时,它将我的消息发送到服务器,但我想将我的消息发送给其他客户端。如何将消息从服​​务器发送到其他客户端,如任何所需客户端。 注释中给出的链接为我提供了一种方式(创建一个全局列表变量,在其中添加每个客户端然后循环并在消息事件中发送消息)将我的消息发送给所有客户端但我也想要我的给特定客户的消息。

1 个答案:

答案 0 :(得分:0)

你需要一些外部系统才能做到这一点。就像本达内尔所说,其他问题解释了一些收集客户的原始方式。

您需要的是在初始化时收集每个客户端的某种ID。这可能是您系统中的帐户,或者您可以为每个新连接生成一个新帐户:

import uuid

clients = {}

class WSHandler(tornado.websocket.WebSocketHandler):
    def __init__(self, application, request, **kwargs):
        super(WSHandler, self).__init__(application, request, **kwargs)
        self.client_id = str(uuid.uuid4())

    def open(self):
        print 'connection for client {0} opened...'.format(self.client_id)
        clients[self.client_id] = self
        self.write_message("The server says: 'Hello'. Connection was accepted.")

    def on_message(self, message):
        self.write_message("The server says: " + message + " back at you")
        print 'received:', message

    def on_close(self):
        clients.pop(self.client_id, None)
        print 'connection closed...'

稍后,您可以使用此完全组成client_id来告诉其他客户端存在具有该ID的客户端。稍后您可以通过

向他发送消息
clients[<id>].write_message("Hello!")

但是,作为旁注,这种方法不会很好地扩展。实际上,您只能处理仅连接到当前龙卷风实例的客户端。如果您需要多个实例以及与任何客户端联系的方式,请参阅rabbitmq等消息代理。

相关问题