Server端的代码
// nodejs的ws
//https://github.com/websockets/ws#broadcast-example
const WebSocket = require("ws");
let wss = new WebSocket.Server({port: 8888}, function(){
console.log("socket server start.");
});
wss.on("connection", ws => {
ws.on("message", msg => {
console.log(msg, " <= 接收client数据");
const data = msg + " Tom";
if (msg.indexOf("all") !== -1) {
console.log("Server广播数据=> ", data);
// 广播
wss.clients.forEach(client => {
client.send(data);
});
return;
}
console.log("Server发送数据=> ", data);
ws.send(data);
});
ws.on("close", () => {
console.log("client主动断开连接.");
});
});
Client端的代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>H5 的WebSocket Client</title>
</head>
<body>
<h1>可以打开多个窗口,验证广播。</h1>
<button onclick="sendAll()">广播</button>
<script>
//H5 的WebSocket
let clent = new WebSocket("ws://localhost:8888");
clent.onopen = function (e) {
let msg = "Hello";//server只接收字符串
console.log("Client发送数据=> ", msg);
clent.send(msg);
};
clent.onclose = function (e) {
console.log("Server主动关闭连接.");
};
clent.onmessage = function (msgEvent) {
console.log(msgEvent.data, "<= 接收来自server的数据");
};
clent.onerror = function (err) {
console.log("出错啦:", err);
};
function sendAll() {
console.log("开始广播,所有的client都会接收到数据。");
clent.send("all");
}
</script>
</body>
</html>