【问题标题】:python tornado websocket server send message to specific clientpython tornado websocket服务器向特定客户端发送消息
【发布时间】:2016-04-19 08:02:05
【问题描述】:

如果多个套接字客户端连接到龙卷风 websocket 服务器,是否可以向特定的客户端发送消息? 我不知道是否有可能获取客户的 id,然后向该 id 发送消息。

我的客户代码是:

from tornado.ioloop import IOLoop, PeriodicCallback
from tornado import gen
from tornado.websocket import websocket_connect


class Client(object):
    def __init__(self, url, timeout):
        self.url = url
        self.timeout = timeout
        self.ioloop = IOLoop.instance()
        self.ws = None
        self.connect()
        PeriodicCallback(self.keep_alive, 20000, io_loop=self.ioloop).start()
        self.ioloop.start()


    @gen.coroutine
    def connect(self):
        print "trying to connect"
        try:
            self.ws = yield websocket_connect(self.url)
        except Exception, e:
            print "connection error"
        else:
            print "connected"

            self.run()

    @gen.coroutine
    def run(self):


        while True:
            msg = yield self.ws.read_message()
            print msg
            if msg is None:
                print "connection closed"
                self.ws = None
                break

    def keep_alive(self):
        if self.ws is None:
            self.connect()
        else:
            self.ws.write_message("keep alive")

if __name__ == "__main__":
    client = Client("ws://xxx", 5 )

【问题讨论】:

    标签: python websocket tornado


    【解决方案1】:

    当您的客户端连接到 websocket 服务器时,将在 WebSocketHandler 上调用方法 'open',在此方法中您可以将 socket 保留在 Appliaction 中。

    像这样:

    from tornado import web
    from tornado.web import url
    from tornado.websocket import WebSocketHandler
    
    
    class Application(web.Application):
        def __init__(self):
            handlers = [
                url(r"/websocket/server/(?P<some_id>[0-9]+)/", WebSocketServer),
            ]
            web.Application.__init__(self, handlers)
            self.sockets = {}
    
    
    class WebSocketServer(WebSocketHandler):
    
        def open(self, some_id):
            self.application.sockets[some_id] = self
    
        def on_message(self, message):
            self.write_message(u"You said: " + message)
    
        def on_close(self):
            print("WebSocket closed")
    

    您也可以使用消息进行连接,在此消息中您必须告诉套接字 id 并将套接字保存到应用程序中。

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 2018-10-25
      • 1970-01-01
      • 2022-07-15
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      • 2015-01-05
      • 2012-06-02
      相关资源
      最近更新 更多