Express 项目环境搭建 -- 20. WebSocket

HTTP 是「请求—响应」模式,服务端无法主动推送。需要实时通知、聊天、协作编辑这类场景时,用 WebSocket。这一篇用 ws 实现,并说明如何与现有 Express 应用共用同一个端口。

基本用法

1
npm install ws
1
2
3
4
5
6
7
8
9
10
const { WebSocketServer } = require("ws");

const wss = new WebSocketServer({ port: 8080 });

wss.on("connection", function connection(ws) {
ws.on("message", function message(data) {
console.log("received: %s", data);
});
ws.send("something");
});

ws 不工作在浏览器里,浏览器端用原生 WebSocket 对象(见参考链接)。

与 Express 共用一个端口

更常见的做法是让 WebSocket 和 HTTP 共用 3000 端口,按路径分流:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const express = require("express");
const { WebSocket, WebSocketServer } = require("ws");

const app = express();
const server = app.listen(3000);

const wss = new WebSocketServer({ noServer: true });

server.on("upgrade", function upgrade(request, socket, head) {
const { pathname } = new URL(request.url, "http://localhost");

if (pathname === "/ws") {
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit("connection", ws, request);
});
} else {
socket.destroy();
}
});

noServer: true 表示不由 ws 自己监听端口,而是由 HTTP server 在收到 upgrade 事件时手动接管。

在 upgrade 阶段鉴权

连接建立前可以检查请求头,拒绝未授权的连接(鉴权逻辑可复用第 8 篇的 token 校验):

1
2
3
4
5
6
7
8
9
server.on("upgrade", function upgrade(request, socket, head) {
const token = request.headers["sec-websocket-protocol"];
if (!verifyToken(token)) {
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
socket.destroy();
return;
}
// ...
});

心跳保活

连接可能因为网络中断而「假死」,用 ping/pong 检测:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
wss.on("connection", function connection(ws) {
ws.isAlive = true;
ws.on("pong", function () {
ws.isAlive = true;
});
});

setInterval(function ping() {
wss.clients.forEach(function each(ws) {
if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, 30000);

广播

向所有已连接客户端发送消息:

1
2
3
4
5
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});

实际项目通常按「房间」或「用户」分组,只推给相关连接,而不是全量广播。

参考链接

系列导航


Express 项目环境搭建 -- 20. WebSocket
https://bubao.github.io/posts/8b9c0d1e.html
作者
一念
发布于
2026年11月21日
许可协议