使用Autobahn/Tisted在TornadoHTTP处理程序中建立websocket连接



问题:客户端发送http请求。对于那个HTTP请求,我希望我的toronto服务器打开一个到外部服务器的websocket连接,并在加班时获得一些数据。(我需要将这些数据存储在数据库中)。我还需要能够处理多个用户对龙卷风服务器的请求。

这是我的实现

from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
from tornado.options import define, options, parse_command_line
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write("This is your response")
factory = WebSocketClientFactory("ws://localhost:7096")
factory.protocol = BridgeSocket
connectWS(factory)
self.finish()
reactor.run()

这是我的套接字连接类:

class BridgeSocket(WebSocketClientProtocol):
def sendHello(self):
self.sendMessage("rails")
def onOpen(self):
self.sendHello()
def onMessage(self, msg, binary):
print "Got echo: " + msg
def onClose(wasClean,code,reason):
print "GETTING CLOSE CONNECTION"
print str(wasClean)+" ---"+str(code)+"---"+str(reason)
reactor.stop()

这里reactor.run()阻止了对Tornado web服务器的进一步http请求,所以我在websocket工作完成并关闭后立即尝试了reactor.stop()。但现在我发现重启反应堆是不可能的。

对于这种方法或我可能遗漏的任何东西,有更好的替代方案吗。。

如果您想在Tornado下从AutobahnPython运行WebSocket客户端,您需要Twisted Tornado集成("Twisted on Tornado")-请参阅此处。这在龙卷风中运行一个扭曲反应堆回路。

最新更新