0

Is it possible, if multiple socket clients are connected to a tornado websocket server, to send a message to a specific one? I don't know if there is a possibility of getting a client's id and then send a message to that 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 )
0

1 Answer 1

1

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.

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.