2016-04-19 131 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,并保存到插座中的应用。

相关问题