1. 程式人生 > 其它 >node是如何實現websocket通訊服務的?

node是如何實現websocket通訊服務的?

在日常開發中,我們難免會遇到客服聊天這樣的業務需求,那麼雙向通訊到底是如何實現的,下面我以node安裝websocket做具體介紹:

首先安裝websocket:npm i ws -S

接著在js檔案中:

//匯入websocket constWebSocket=require("ws");
//建立socket伺服器並監聽 constwss=newWebSocket.Server({port:3000});
//監聽客戶端連線,並建立客戶端socket wss.on("connection",functionconnection(client){ //監聽客戶端傳送的資料 client.on("message",functionincoming(message){ console.log("received:%s",message); });
//監聽客戶端連線關閉 client.on("close",function(){ console.log("close"); clearInterval(timer); });
//傳送資料 consttimer=setInterval(()=>{ constres={ code:0, msg:"ok", action:"getServerTime", data:[ {id:1,name:"Rose"}, {id:2,name:"Jack"}, ], }; client.send(JSON.stringify(res)); },1000); });
console.log("socket伺服器已啟動...");

在客戶端這樣寫:

<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"/> <metahttp-equiv="X-UA-Compatible"content="IE=edge"/> <metaname="viewport"content="width=device-width,initial-scale=1.0"/> <title>Document</title> </head> <body> <div>當前時間:<span></span></div> <button>向伺服器傳送訊息</button> <script> varclient=newWebSocket("ws://127.0.0.1:3000");
client.onopen=function(){ console.log("連線成功"); }; client.onclose=function(){ console.log("斷開連線"); }; client.onerror=function(ex){ console.log("socket通訊過程中的錯誤",ex); }; client.onmessage=function(res){ console.log(JSON.parse(res.data)); //document.querySelector("span").innerText=res.data; };
document.querySelector("button").onclick=function(){ constreq={ action:"getServerTime", params:{ id:1, name:"xxxx", }, }; client.send(JSON.stringify(req)); }; </script> </body> </html>