Pregunta

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..

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top