简体   繁体   English

python龙卷风websocket服务器将消息发送到特定客户端

[英]python tornado websocket server send message to specific client

Is it possible, if multiple socket clients are connected to a tornado websocket server, to send a message to a specific one? 如果多个套接字客户端连接到龙卷风websocket服务器,是否可以向特定的消息发送消息? I don't know if there is a possibility of getting a client's id and then send a message to that id. 我不知道是否有可能获取客户的ID,然后向该ID发送消息。

My client code is: 我的客户代码是:

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 )

When your client connects to the websocket server will be invoked method 'open' on WebSocketHandler, in this method you can keep socket in the Appliaction. 当您的客户端连接到Websocket服务器时,将在WebSocketHandler上调用方法“ open”,在此方法中,您可以将套接字保留在Appliaction中。

Like this: 像这样:

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

You also may use message for connection, in this message you have to tell socket id and save socket into the Application. 您也可以使用消息进行连接,在此消息中,您必须告诉套接字ID并将套接字保存到应用程序中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM