2016-07-29 40 views
0

我目前正在嘗試每次調用某個函數時都使用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_messageWebSocketHandler但我很困惑它的實例是什麼?我不斷遇到的錯誤是self isn't defined,但我不知道什麼是自己是什麼?我知道WebSocketHandler獲取運行每當客戶端嘗試加載^/WEB$

編輯:這裏是我的server.py文件,我需要調用write_message在itercheckers

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() 
+0

你如何訪問它?你不去ws:// localhost:8000/ws?你必須用js製作html頁面,並在該頁面打開控制檯,看看輸出是什麼 –

+0

不,我不知道。訪問WebSocketHandler的鏈接是「/ WEB」。 '新的WebSocket(「ws:// localhost:8008/WEB」);'連接我 –

回答

0
spawn callback電話

第一件事,第一,self關鍵字之後指向當前處理的當前websocket客戶端。要使用龍捲風的WebSockets,你必須初始化龍捲風應用

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 "); 
    }; 
} 

我還沒有測試過,但應該可以工作

+0

對不起,我應該包括它,但我有一個'server.py'文件,我創建'web.Application'並傳遞一個列表處理程序。我可以將我的客戶端連接到服務器。我試圖弄清楚的是如何基於服務器端事件從服務器向客戶端發送數據。 –

+0

你想發送給特定客戶或所有客戶 –

+0

所有客戶。這是一個狀態儀表板,我需要更新,每當一個特定的功能被稱爲 –