龙卷风 - 如何在另一个函数中调用处理程序

时间:2016-07-29 18:50:30

标签: javascript python-3.x websocket tornado

我目前正在尝试使用Tornado的Web套接字处理程序在每次调用某个函数时更新仪表板。这是处理程序:

class WebSocketHandler(websocket.WebSocketHandler):
    clients = []
    def open(self):
        logging.info("WEBSOCKET OPEN")
        WebSocketHandler.clients.append(self)
    def on_message(self, message):
        logging.info("message from websocket recieved")
        self.write_message("WebSocket connected")
    def on_close(self):
        logging.info("WEBSOCKET closed")

这是客户端脚本,它在加载时连接WebSocket:

  function WebSocketTest()
{ var ws = 0;
   ws = new WebSocket("ws://localhost:8008/WEB");
   ws.onopen = function()
    {
    ws.send("initial connect")
    }

  ws.onmessage = function (evt)
  {
    console.log(evt.data)
  };

  ws.onclose = function()
  {
    console.log("closed ");
  };
}

websockets连接成功。

我需要从write_message拨打WebSocketHandler,但我很困惑它的实例是什么?我一直遇到的错误是self isn't defined,但我不确定自己到底是什么?我知道只要客户端尝试加载WebSocketHandler

,就会运行^/WEB$

编辑:这是我的server.py文件,我需要在spawn callback

中的itercheckers电话后立即拨打write_message
class Server():



@classmethod
def run(cls):
    options.parse_command_line()
    # Start web
    template_path = os.path.join(os.path.dirname(__file__), 'templates')
    jinja2loader = Jinja2Loader(template_path)
    kwargs = dict(
        template_loader=jinja2loader,
        static_path=os.path.join(os.path.dirname(__file__), 'static'),
        debug=True,
        login_url="/auth/login",
        cookie_secret="dn470h8yedWF9j61BJH2aY701i6UUexx"
    )
    app = web.Application(handlers, **kwargs).listen(
        configuration['server']['port'],)

    # Reset events
    @gen.coroutine
    def reset(parent=None):
        if parent is None:
            parent = configuration
        # Reset event happyness
        yield events.reset_happy(parent)
        # Read last status
        data = yield events.get(parent)
        # Read and set happy from the last status
        happy = (data or {}).get('status', events.STATUS_OK) \
            in events.HAPPY
        yield events.set_happy(parent, happy)
        # Iterate sub-events
        for event in parent['events']:
            yield reset(event)

    ioloop.IOLoop.current().run_sync(reset)



    # Start checkers
    def itercheckers(parent):
        index = 0
        for event in parent.get('events', []):
            if 'checker' in event:
                checker = event['checker']
                p, m = checker['class'].rsplit('.', 1)
                ioloop.IOLoop.current().spawn_callback(
                    getattr(importlib.import_module(p), m)(
                        event=event,
                        frequency=checker.get('frequency', 1),
                        params=checker['params']
                    ).run)
            index += 1
            itercheckers(event)
    itercheckers(configuration)



    # Start alerts
    ioloop.IOLoop.current().run_sync(alerts.reset)
    for alert in configuration['alerts']:
        p, m = alert['class'].rsplit('.', 1)
        ioloop.IOLoop.current().spawn_callback(
            getattr(importlib.import_module(p), m)(
                alert=alert
            ).run
        )

    # Start loop
    ioloop.IOLoop.current().start()

1 个答案:

答案 0 :(得分:0)

首先,self关键字指向当前处理的当前websocket客户端。要使用tornado websockets,您必须初始化tornado app

app = web.Application([
    (r'/ws', WSHandler), #tells it to redirect ws:// to websocket handler
#Choose different names from defaults because of clarity
])

if __name__ == '__main__':
    app.listen(5000) #listen on what port
    ioloop.IOLoop.instance().start()

然后你必须有WSHandler类,你指的是websockets trafic到

class WSHandler(websocket.WebSocketHandler):
    #crossdomain connections allowed
    def check_origin(self, origin):
        return True
    #when websocket connection is opened
    def open(self):
       print("Client connected ")

    def on_close(self):
       print("Client disconnected")

    def on_message(self,message):
       self.write_message(message) #echo back whatever client sent you

如此完整的应用程序看起来像

from tornado import websocket, web, ioloop
clients = [] 

#whenever you want to broadcast to all connected call this function
def broadcast_message(msg):
    global clients 
    for client in clients:
        client.write_message(msg)

class WSHandler(websocket.WebSocketHandler):
    #crossdomain connections allowed
    def check_origin(self, origin):
        return True
    #when websocket connection is opened
    def open(self):
       #here you can add clients to your client list if you want
       clients.append(self)
       print("Client connected ")

    def on_close(self):
       clients.remove(self)
       print("Client disconnected")

    def on_message(self,message):
       self.write_message(message) #echo back whatever client sent you

app = web.Application([
    (r'/ws', WSHandler), #tells it to redirect ws:// to websocket handler
#Choose different names from defaults because of clarity
])

if __name__ == '__main__':
    app.listen(5000) #listen on what port
    ioloop.IOLoop.instance().start()

现在用js连接到它

function WebSocketTest()
{ 
   var ws = new WebSocket("ws://localhost:5000/ws");
    ws.onopen = function()
    {
       ws.send("initial connect")
    }

    ws.onmessage = function (evt)
    {
       console.log(evt.data) 
    };

    ws.onclose = function()
    {
       console.log("closed ");
    };
}

我没有测试过,但应该可以使用