简体   繁体   中英

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

Problem: Client sends in a http request. 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). 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:

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. 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 . This runs a Twisted reactor loop within Tornado.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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