-->

can a single instance of websocket[tornado] to han

2019-09-09 23:45发布

问题:

I work on a project which uses Ajax and Websockets. The task is to get rid of the Ajax and to use Websockets only. On the server side I'm using tornado and django with a tornado-url-dispatcher. I want to reuse some methods already defined in django using a single instance of websocket(tornado.websocket.WebSocketHandler). This class has 3 default handlers but I extended it by adding new handlers which redirects to the existent django methods and modified the dispatcher to point to the new methods.

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        ...
    def on_message(self, message):
        ...
    def on_close(self):
        ...
    def new_handler_1(self, request):
        ...

tornado_app = tornado.web.Application(
    [
      (r'/ws/new_handler', wshandler.WSHandler.new_handler_1),
      (r'/ws', wshandler.WSHandler),
    ]

What type of response shall I use in order to reply from new_handler_1 method to a request done via a websocket ? Thanks.

回答1:

You can't do this; a new instance of the handler class is created for every request. Instead, make some other shared object that the handlers can use to communicate between themselves. You can pass this object to the handlers either by attaching it to the Application object or passing it as an initialize argument to the handler.