2012-11-12 109 views
2

我想添加一個sockjs龍捲風服務器到我的網站,並且一切正常,直到我決定通過MsgPack(使用msgpack-rpc-python)將它連接到我的其他應用程序。現在可以使用sockjs服務器或者RPC服務器。取決於他們哪些從那裏開始循環。Sockjs龍捲風和rpc

我認爲我需要爲他們兩個使用一個tornado.ioloop。但不知道如何實現它。或者可能有另一種方法將rpc添加到龍捲風服務器上?

這裏是一個sockjs,龍捲風樣本代碼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() 

`

任何建議或例子,歡迎!

回答

1

發生這種情況是因爲兩個start()調用都啓動了Tornado IOLoop,並且在IOLoop停止之前它們不會退出。

是的,你必須使用一個IOLoop。作爲msgpackrpc.Server接受Loop類的實例和Loop incapsulates IOLoop,試試這個:

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() 
+0

真棒!像魅力一樣工作。非常感謝! – Jerry92