简体   繁体   English

使用Autobahn / Twisted在Tornado HTTP Handler中建立websocket连接

[英]Using Autobahn/Twisted to establish a websocket connection in Tornado HTTP Handler

Problem: Client sends in a http request. 问题:客户端发送http请求。 For that HTTP request, I want my tornado server to open a websocket connection to an external server and get some data overtime.(That data I need to store in the database). 对于那个HTTP请求,我希望我的龙卷风服务器打开到外部服务器的websocket连接,并获得一些超时的数据。(我需要存储在数据库中的数据)。 I also need to be able to handle multiple user requests to the tornado server. 我还需要能够处理龙卷风服务器的多个用户请求。

Here's my implementation 这是我的实施

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

And here's my Socket connection class: 这是我的Socket连接类:

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

Here reactor.run() prevents further http requests to the Tornado web server, so I tried reactor.stop() as soon as the websocket work is done and is closed. 这里reactor.run()阻止了对Tornado Web服务器的进一步http请求,所以我在websocket工作完成并关闭后尝试了reactor.stop()。 But now I found out that it is not possible restart reactor. 但现在我发现重启反应堆是不可能的。

Is there any better alternative for the approach or anything I might be missing.. 是否有更好的替代方法或我可能会遗漏的任何东西..

If you want to run the WebSocket client from AutobahnPython under Tornado, you need the Twisted-Tornado integration ("Twisted on Tornado") - see here . 如果你想从Tornado 下的 AutobahnPython运行WebSocket客户端,你需要Twisted-Tornado集成(“Twisted on Tornado”) - 请看这里 This runs a Twisted reactor loop within Tornado. 这在Tornado内运行Twisted反应器循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM