使用websocket建立客戶端與服務器的雙向連接
實現效果:
實現代碼:
1.init方法:
init: function () { if(typeof(WebSocket) === "undefined"){ alert("您的瀏覽器不支持socket") }else{ // 實例化socket this.socket = new WebSocket(this.path) // 監聽socket連接 this.socket.onopen = this.open // 監聽socket錯誤信息 this.socket.onerror = this.error // 監聽socket消息 this.socket.onmessage = this.getMessage //關閉socket連接 this.socket.onclose = this.websocketclose } },
path變量:
export var pathFile = "ws://192.168.1.145:8081/hawkeye/"; path: pathFile+"webSocket/",
2.建立連接:
open: function (e) { let data = this.network+"_"+this.partition+"_nodeId"; this.send(data); console.log("socket連接成功") },
3.給服務端發送消息:
send: function (Data) { this.socket.send(Data); },
4.接收消息:
getMessage: function (msg) { var data = JSON.parse(msg.data); }
5.斷開連接:
websocketclose(e){ //關閉 console.log('斷開連接',e); },
6.錯誤提醒方法:
error: function () { console.log("連接錯誤") },
注意:
1.可以手動關閉websocket連接:this.socket.close();
2.若是需要在某種情況下要重新給服務端發送數據,可以直接let data = this.network+"_"+this.partition+"_nodeId"; this.send(data);因為一直處於連接中
3.若是在一進來頁面就要開始websocket連接,可以直接在open建立連接時就發送數據。
4.雙向通信時都是使用string字符串傳輸。