1. 程式人生 > >web socket 入門

web socket 入門

alert ble 單個 data font onerror exceptio mat size

WebSocket是HTML5開始提供的一種在單個 TCP 連接上進行全雙工通訊的協議,其優雅地解決了以往web服務器不能向web客戶端實時推送消息的問題。

在瀏覽器js環境中,創建一個websocket對象如下所示:

var ws = New WebSocket(url, [protocol])

第一個參數 url, 指定連接的 URL,一般web服務器會對這個url進行特殊的處理,一般會用實現了websocket協議的handler處理websocket請求。

第二個參數 protocol 是可選的,指定了可接受的子協議。

WebSocket事件

websocket提供了四個回調函數,分別用來處理open,close,message,error四個事件,即ws.onopen,ws.onclose,ws.onmessage,ws.onerror

舉個栗子:

var ws_req = {
socket: null,
start: function() {
var Is_Flash_running = false;
var total_fail_count = 0;
if ("WebSocket" in window) {
var url = "ws://" + location.host + "/socket_req";
if (ws_req.socket){
ws_req.socket.close();
}
ws_req.socket = new WebSocket(url);
ws_req.socket.onopen = function() {
console.log("Opening a connection...");
ws_req.socket.send("connect to web server......")
};
ws_req.socket.onclose = function(evt) {
console.log("I‘m sorry. Bye!");
};
ws_req.socket.onerror = function(evt) {
console.log("ERR: " + evt.data);
};
ws_req.socket.onmessage = function(event) {
try {
handleMessage(event.data);
} catch (err) {
console.log(err);
}
}
} else {
alert(‘你的瀏覽器太落伍了,換用高版本的chrome內核瀏覽器吧!!!‘);
}
},
}
ws_req.start();

var handleMessage = function(data){
//
}

web服務器實現:

筆者使用的後端開發語言是python,用的是Tornado web框架,tornado.websocket已經封裝了websocket的協議,我們僅需簡單的調用即可

import tornado.web
import tornado.websocket
import traceback

from device_serial_load import DevSerialLoadHandler
class LoadDevSerialSocketHandler(tornado.websocket.WebSocketHandler): client
= set() def get_compression_options(self): # Non-None enables compression with default options. return {} def open(self): LoadDevSerialSocketHandler.client.add(self) def on_close(self): LoadDevSerialSocketHandler.client.remove(self) try: self.dslhler.dev_serial_load_client.stop() except Exception, e: logger.info(close socket client) def send_msg_to_broswer(self, msg): try: self.write_message(msg) return True except: logger.error(str(msg) + 發送失敗) self.close() return False def on_message(self, message): message_json = json.loads(message) if "NodeID" in message_json and "LineNum" in message_json : node_ip = TestNodeData().get_node_ip(message_json["NodeID"]) line_num = message_json["LineNum"][2] self.dslhler = DevSerialLoadHandler(node_ip, line_num, self.send_msg_to_broswer) self.dslhler.start() elif "InputMessage" in message_json: try: if message_json["InputMessage"] == "None": # 支持網頁僅回車鍵的發送 self.dslhler.dev_serial_load_client.client.send(" ") else: self.dslhler.dev_serial_load_client.client.send(message_json["InputMessage"]) except Exception, e: logger.error(e) logger.error(traceback.format_exc()) logger.error("send input message to dev serial fail") self.send_msg_to_broswer("<span style=‘color:red;font-size:20px‘>ATCServer:[串口命令發送失敗]</span>\r\n")

上訴代碼將串口打印通過websocket實時的傳輸到web頁面顯示

web socket 入門