python-websocket-server hacking
阿新 • • 發佈:2017-10-06
*** 目前 on() onsubmit host and pytho head tput
/************************************************************************* * python-websocket-server hacking * 說明: * 跟一下python-websocket-server怎麽使用,這個lib還算是目前想用的。 * * 2017-10-6 深圳 南山平山村 曾劍鋒 ************************************************************************/ 一、參考文檔: https://github.com/ZengjfOS/python-websocket-server 二、client.html <html> <head> <title>Simple client</title> <script type="text/javascript"> var ws; function init() { // Connect to Web Socketws = new WebSocket("ws://localhost:9001/"); // Set event handlers. // 連接WebSocket服務器成功,打開成功 ws.onopen = function() { output("onopen"); }; // 收到WebSocket服務器數據 ws.onmessage = function(e) { // e.data contains received string.output("onmessage: " + e.data); }; // 關閉WebSocket連接 ws.onclose = function() { output("onclose"); }; // WebSocket連接出現錯誤 ws.onerror = function(e) { output("onerror"); console.log(e) }; } // 將當前文本框中的內容發送到WebSocket function onSubmit() { var input = document.getElementById("input"); // You can send message to the Web Socket using ws.send. ws.send(input.value); output("send: " + input.value); input.value = ""; input.focus(); } // 關閉WebSocket連接 function onCloseClick() { ws.close(); } // 在界面上顯示接收到的數據,將替換掉一些需要轉義的字符 function output(str) { var log = document.getElementById("log"); var escaped = str.replace(/&/, "&").replace(/</, "<"). replace(/>/, ">").replace(/"/, """); // " log.innerHTML = escaped + "<br>" + log.innerHTML; } </script> </head> <!-- 文檔加載完畢之後,會調用init函數進行處理 --> <body onload="init();"> <!-- 點擊submit之後,調用onSubmit函數 --> <form onsubmit="onSubmit(); return false;"> <!-- 發送數據的輸入框 --> <input type="text" id="input"> <input type="submit" value="Send"> <!-- 點擊關閉按鈕關閉WebSocket連接 --> <button onclick="onCloseClick(); return false;">close</button> </form> <!-- 顯示發送、接收到數據 --> <div id="log"></div> </body> </html> 三、server.py # 加載WebsocketServer模塊 from websocket_server import WebsocketServer # Called for every client connecting (after handshake) def new_client(client, server): print("New client connected and was given id %d" % client[‘id‘]) # 發送給所有的連接 server.send_message_to_all("Hey all, a new client has joined us") # Called for every client disconnecting def client_left(client, server): print("Client(%d) disconnected" % client[‘id‘]) # Called when a client sends a message def message_received(client, server, message): if len(message) > 200: message = message[:200]+‘..‘ print("Client(%d) said: %s" % (client[‘id‘], message)) # 發送給所有的連接 server.send_message_to_all(message) # Server Port PORT=9001 # 創建Websocket Server server = WebsocketServer(PORT) # 有設備連接上了 server.set_fn_new_client(new_client) # 斷開連接 server.set_fn_client_left(client_left) # 接收到信息 server.set_fn_message_received(message_received) # 開始監聽 server.run_forever()
python-websocket-server hacking