python tornado websocket server send message to specific client -
is possible, if multiple socket clients connected tornado websocket server, send message specific one? don't know if there possibility of getting client's id , send message id.
my client code is:
from tornado.ioloop import ioloop, periodiccallback tornado import gen 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 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 none: print "connection closed" self.ws = none break def keep_alive(self): if self.ws none: self.connect() else: self.ws.write_message("keep alive") if __name__ == "__main__": client = client("ws://xxx", 5 )
when client connects websocket server invoked method 'open' on websockethandler, in method can keep socket in appliaction.
like this:
from tornado import web tornado.web import url 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 may use message connection, in message have tell socket id , save socket application.
Comments
Post a Comment