--------------------------- 再不学习就去要饭 ------------------------
有写广播的方法,但是感觉不好,不知道有没有其他方法,有的话请分享一下呀~
服务端
const WebSocket = require('ws'); // 需要先安装ws npm i --save ws
const ws = new WebSocket.Server({port: 8080}, () => {
console.log('socket start');
})
let clients = [];
ws.on('connection', (client) => {
// 每个客户端连接时创建一个client,广播时要发给每一个,所以要把创建的client都丢到一个数组里面。
clients.push(client);
client.send('欢迎光临'); // 数据传输字符串
client.on('message', (msg) =>{
console.log('来自前端的数据:'+ msg);
if(msg.includes('广播')){
sendAll();
}
})
client.on('close', (msg) =>{
console.log('前端主动断开连接');
})
})
// 广播发送给每个客户端
function sendAll() {
for (let index = 0; index < clients.length; index++) {
clients[index].send('开始📢:略略略略略~~~');
}
}
客户端
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WS</title>
</head>
<body>
<input type="text" id="message">
<button onclick="sendServer()">send server</button>
<script>
// 创建 WebSocket 对象
const ws = new WebSocket('ws://localhost:8080/');
// 连接建立时触发
ws.onopen = function () {
console.log('WebSocket已连接');
// 使用连接发送数据
ws.send('Hello!');
};
// 客户端接收服务端数据时触发
ws.onmessage = function (msg) {
console.log('来自服务器端数据:', msg.data); // MessageEvent {isTrusted: true, data: "欢迎光临" ...}
alert(msg.data);
// 关闭连接
// ws.close();
};
// 通信发生错误时触发
ws.onerror = function (e) {
console.log(e);
};
// 连接关闭时触发
ws.onclose = function () {
console.log('WebSocket已关闭');
}
function sendServer() {
let message = document.getElementById('message').value;
ws.send(message);
}
</script>
</body>
</html>