簡體   English   中英

python龍卷風websocket服務器將消息發送到特定客戶端

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

如果多個套接字客戶端連接到龍卷風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 )

當您的客戶端連接到Websocket服務器時,將在WebSocketHandler上調用方法“ open”,在此方法中,您可以將套接字保留在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並將套接字保存到應用程序中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM