主要實現一個客戶端給服務端發送消息,服務端再推送給客戶端,其中客戶端是有多個
首先來看一下效果
具體代碼實現:
服務端:
首先需要安裝依賴
npm i nodejs-websocket -S
然后新建一個app.js文件
app.js代碼如下:
-
const ws =
require(
'nodejs-websocket');
//引入websocket
-
const prot =
8088;
-
-
const server = ws.createServer(
connection => {
-
// console.log('有一名用戶連接進來了...')
-
connection.on(
"text",
function (str) {
-
// console.log('我來接收客戶端發過來的消息' + str)
-
// connection.sendText(str);//返回給客戶端的數據
-
server.connections.forEach(
function (conn) {
-
conn.sendText(str)
//返回給所有客戶端的數據(相當於公告、通知)
-
})
-
})
-
//監聽關閉
-
connection.on(
"close",
function (code, reason) {
-
console.log(
"Connection closed")
-
})
-
//監聽異常
-
connection.on(
"error",() => {
-
console.log(
'服務異常關閉...')
-
})
-
}).listen(prot)
客戶端:
此處略過客戶端的css部分,因為並不好看
-
<!-- html -->
-
-
<!DOCTYPE html>
-
<html>
-
<head>
-
<meta charset="utf-8" />
-
<meta name="viewport" content="width=device-width, initial-scale=1">
-
<link rel="stylesheet" type="text/css" href="./css/cssReset.css"/>
-
<link rel="stylesheet" type="text/css" href="./css/index.css"/>
-
<title>
</title>
-
</head>
-
<body>
-
<div id="box">
-
<div class="msg" id="msg">
</div>
-
<div class="bottom">
-
<input type="text" id="inp" value="" />
-
<button type="button" id="btn">提交
</button>
-
</div>
-
</div>
-
-
<script type="text/javascript" src="./js/index.js">
</script>
-
</body>
-
</html>
-
//javascript
-
-
let ws =
new WebSocket(
'ws://localhost:8088');
//實例化websocket
-
-
let val =
'';
-
let btn =
document.getElementById(
'btn');
//發消息按鈕
-
let msg =
document.getElementById(
'msg');
//存消息容器
-
-
//發消息
-
ws.onopen =
function(){
-
//點擊按鈕發送消息
-
btn.onclick =
function(){
-
val =
document.getElementById(
'inp').value;
-
ws.send(val);
//發送給服務端數據
-
}
-
};
-
-
//收消息
-
ws.onmessage =
function (e) {
-
//e 接收服務端返回的數據
-
var received_msg = e.data;
-
msg.innerHTML += received_msg +=
'<br>'
-
};
-
-
//關閉連接
-
ws.onclose =
function(){
-
console.log(
"連接已關閉...");
-
};
-
-
//拋錯
-
ws.onerror =
function () {
-
console.log(
'服務異常關閉...')
-
}
此處粘貼一個 nodejs-websocket 在npm上的文檔 點擊查看