NodeJS中WebSocket服务器

服务器

添加依赖

1
npm install ws

server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const WebSocket = require('ws');
const http = require('http');

// 创建一个 HTTP 服务器
const server = http.createServer();

// 创建一个 WebSocket 服务器并将其绑定到 HTTP 服务器
const wss = new WebSocket.Server({ server });

// 存储所有连接的客户端
const clients = new Set();

// 处理连接事件
wss.on('connection', (ws) => {
console.log('客户端连接成功');

// 将新连接的客户端添加到 clients 集合中
clients.add(ws);

// 处理接收到的消息
ws.on('message', (message, isBinary) => {
if (!isBinary) {
// 广播消息给所有其他客户端
for (let client of clients) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`${message}`);
}
}
}
});

// 处理客户端断开连接
ws.on('close', () => {
console.log('客户端断开连接');
// 从 clients 集合中移除断开的客户端
clients.delete(ws);
});
});

// 启动 HTTP 服务器
server.listen(8081, () => {
console.log('WebSocket 服务器正在运行在 ws://localhost:8081');
});

message的类型是Buffer,不能通过它获取消息的类型,是字符串还是二进制数据。

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>客户端</title>
</head>

<body>
<h1>聊天室</h1>
<div id="content" name="name" style="overflow-y: scroll; width: 400px; height: 300px; border: solid 1px #000"></div>
<br />
<div>
<input type="text" id="msg" style="width: 200px;">
</div>
<button id="submit">提交</button>
<script>
document.querySelector('#submit').addEventListener('click', function () {
var msg2 = msg.value
ws.send(msg2)
msg.value = ''
}, false);

// 客户端连接到服务端配置
const ws = new WebSocket("ws://127.0.0.1:8081"); //连接到客户端

//上线
ws.onopen = () => {

};
//发送信息
ws.onmessage = (msg) => {
const content = document.getElementById("content");
content.innerHTML += msg.data + "<br>";
};
//报错
ws.onerror = (err) => {
console.log(err);
};

//下线
ws.onclose = () => {
console.log("close");
};

</script>
</body>
</html>

发送二进制

1
2
3
4
5
6
if (ws && ws.readyState == socket.OPEN) {
let buffer = new ArrayBuffer(1); // 初始化1个Byte的二进制数据缓冲区
let dataView = new DataView(buffer);
dataView.setInt8(0, 127);
ws.send(dataView);
}