2016-04-19 178 views
0

如果多個套接字客戶端連接到龍捲風websocket服務器,是否可能發送消息到特定的客戶端? 我不知道是否有可能獲取客戶端的ID,然後發送消息到該ID。蟒蛇龍捲風websocket服務器發送消息到特定的客戶端

我的客戶端代碼:

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) 

回答

0

當你的客戶端連接到服務器的WebSocket將被調用方法上WebSocketHandler「開放式」,在這種方法你可以保持插座在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,並保存到插座中的應用。

相關問題