Search code examples
pythonwebsocketcallbacktornado

Tornado websocket callback on_message


i achieved to have two threads working in my python application. Now i want to add a callback function to the on_message to handle the receiving message in another thread.

here is my code:

import tornado.websocket
import tornado.web
import message.MessageHandler

from message.messageConstructor import MessageConstructor


class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
        self.send(message.MessageHandler.serialize(MessageConstructor('Engine1', '100')))
        self.send("CONNECT!")

    def on_message(self, rawMessage):
        print rawMessage
        obj = message.MessageHandler.deserialize(rawMessage)
        callback(message)

    def on_close(self):
        print 'connection closed'

    def check_origin(self, origin):
        return True

    def send(self, message):
        self.write_message(message)

and the creation:

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import socket

from websocket import connectionHandler


class WebSocketConnection():
    def __init__(self, port, callback):
        self.socketHandler = connectionHandler.WebSocketHandler

        application = tornado.web.Application([
            (r'/', self.socketHandler),
        ])

        callback("World")

        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(7004)
        myIP = socket.gethostbyname(socket.gethostname())
        print '*** Websocket Server Started at %s***' % myIP
        tornado.ioloop.IOLoop.instance().start()

    def send(self, message):
        self.socketHandler.send(message)

how can i provide a callback to the not instantiated instance of the WebsocketHandler?


Solution

  • You can use RequestHandler.initialize to pass configuration through the Application to the handlers:

    class WebSocketHandler(tornado.websocket.WebSocketHandler):
        def initialize(self, callback):
            self.callback = callback
    
    app = Application([('/', WebSocketHandler, dict(callback=callback))])