Вопрос

I'm trying to add a sockjs-tornado server to my site, and all worked fine until I decided to connect it to my other apps via MsgPack (using msgpack-rpc-python). And now works sockjs server either RPC server. Depending on wich of them start there loop first.

I think that I need to use one tornado.ioloop for both of them. But do not know how to achieve it. Or may be there is another way to add rpc to a tornado server?

Here is a sockjs-tornado sample code with msgpack-rpc-python:

import tornado.ioloop
import tornado.web

import sockjs.tornado

import msgpackrpc

class RPCServer(object):
    def sum(self, x, y):
        return x + y

class IndexHandler(tornado.web.RequestHandler):
    """Regular HTTP handler to serve the chatroom page"""
    def get(self):
        self.render('index.html')

class ChatConnection(sockjs.tornado.SockJSConnection):
    """Chat connection implementation"""
    # Class level variable
    participants = set()

    def on_open(self, info):
        # Send that someone joined
        self.broadcast(self.participants, "Someone joined.")
        # Add client to the clients list
        self.participants.add(self)

    def on_message(self, message):
        # Broadcast message
        self.broadcast(self.participants, message)

    def on_close(self):
        # Remove client from the clients list and broadcast leave message
        self.participants.remove(self)
        self.broadcast(self.participants, "Someone left.")

if __name__ == "__main__":
    # 1. Create chat router
    ChatRouter = sockjs.tornado.SockJSRouter(ChatConnection, '/chat')

    # 1.5 Create MsgPack RPC Server
    rpc = msgpackrpc.Server(RPCServer())

    # 2. Create Tornado application
    app = tornado.web.Application(
            [(r"/", IndexHandler)] + ChatRouter.urls
    )

    # 3. Make Tornado app listen on port 5000
    app.listen(5000)

    # 3.5 Make MsgPack RPC Server listen on port 5001
    rpc.listen(msgpackrpc.Address('localhost', 5001))

    # 4. Start IOLoop
    tornado.ioloop.IOLoop.instance().start()

    # 5. Never executed 
    rpc.start()

`

Any suggestions or examples are welcome!

Это было полезно?

Решение

This happens because both start() calls start Tornado IOLoop and they won't exit until IOLoop stopped.

Yes, you have to use one IOLoop. As msgpackrpc.Server accepts Loop class instance and Loop incapsulates IOLoop, try this:

if __name__ == '__main__':
    io_loop = tornado.ioloop.IOLoop.instance()

    loop = msgpackrpc.Loop(io_loop)
    rpc = msgpackrpc.Server(RPCServer(), loop=loop)

    # ... sockjs-tornado initialisation. No need to call rpc.start()

    io_loop.start()
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top