Tornado websocket回调on_message

时间:2016-05-13 07:22:23

标签: python websocket callback tornado

我实现了在我的python应用程序中运行两个线程。 现在我想在on_message中添加一个回调函数来处理另一个线程中的接收消息。

这是我的代码:

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)

和创作:

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)

如何为未实例化的WebsocketHandler实例提供回调?

1 个答案:

答案 0 :(得分:1)

您可以使用RequestHandler.initialize将应用程序中的配置传递给处理程序:

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def initialize(self, callback):
        self.callback = callback

app = Application([('/', WebSocketHandler, dict(callback=callback))])