我正在尝试将 sockjs-tornado 服务器添加到我的站点,并且一切正常,直到我决定通过 MsgPack(使用 msgpack-rpc-python)将它连接到我的其他应用程序。现在可以使用 sockjs 服务器或者 RPC 服务器。取决于它们中的哪一个首先开始循环。
我认为我需要为他们两个使用一个 tornado.ioloop。但不知道如何实现。或者可能有另一种方法将 rpc 添加到龙卷风服务器?
这是带有 msgpack-rpc-python 的 sockjs-tornado 示例代码:
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()
`
欢迎任何建议或示例!