WebSocket是原生轻量协议,适合现代浏览器;Socket.IO是其上层库,提供降级、房间、重连等能力。原生需手动处理JSON、无内置重连;Socket.IO需动态引入客户端脚本并注意跨域与Nginx配置。
WebSocket 是浏览器原生支持的实时通信协议,Socket.IO 是基于 WebSocket 的上层库,自带降级和心跳机制;如果只需要现代浏览器支持、追求轻量,直接用 WebSocket;如果要兼容老旧环境、需要广播、房间、自动重连等能力,选 socket.io。
原生 WebSocket 没有内置重连、消息确认或房间管理,但开销小、可控性强。服务端必须用支持 WebSocket 协议的库,如 ws(不是 websocket 或 node-websocket)。
new WebSocket("ws://localhost:8080") 必须用 ws://(开发)或 wss://(生产),HTTP 地址会直接报 SecurityError
ws 库监听时,不能直接挂载在 http.Server 上处理所有请求——它只响应 Upgrade 请求,其他路径需单独配静态服务或反向代理ws 实例没有 emit/on,而是用 send() 和 on("message", ...);发送非字符串数据需先 JSON.stringify(),接收后手动 JSON.parse()
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws, req) => {
console.log('client connected from', req.socket.remoteAddress);
ws.send(JSON.stringify({ type: 'welcome', time: Date.now() }));
ws.on('message', (data) => {
try {
const msg = JSON.parse(data.toString());
console.log('received:', msg);
ws.send(JSON.stringify({ echo: msg }));
} catch (e) {
ws.close(4001, 'invalid json');
}
});
});
socket.io 默认启用长轮询降级,首次连接可能走 XHR 而非 WebSocket,这是正常行为;若明确禁用降级,需两端同步配置 transports: ['websocket'],否则服务端仍会接受轮询请求,客户端却拒绝响应。
socket.io 后,不要用 http.createServer().listen() 再传给 io();推荐直接 io.listen(3000),避免中间件干扰升级头;硬写 CDN 链接会导致跨域或版本不匹配,表现为 io is not defined 或连接后无 connect 事件socket.join("room-123") 不会自动广播给房间内其他人,需显式调用 io.to("room-123").emit(...);socket.emit() 只发给自己,socket.broadcast.emit() 发给除自己外的当前连接所有人// server.js
const http = require('http');
const express = require('express');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: { origin: "http://localhost:5173", methods: ["GET", "POST"] }
});
io.on('connection', (socket) => {
socket.join('general');
socket.on('chat', (msg) => {
io.to('general').emit('chat', { user: socket.id, text: msg });
});
});
server.listen(3000);
90% 的连接问题出在协议、路径或跨域配置,而不是代码逻辑。先确认基础链路是否通,再加业务逻辑。
W
ebSocket connection to 'ws://...' failed:检查服务端是否真正监听了该地址+端口,用 curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" http://localhost:8080 模拟 Upgrade 请求看响应头是否含 101 Switching Protocols
transport close:大概率是前端 io() 调用时没传 { transports: ['websocket'] },而后端又没配 CORS,导致预检请求被拦截socket.emit() 误以为是广播;或者服务端用了 socket.broadcast.emit() 却期望自己也能收到proxy_http_version 1.1;、proxy_set_header Upgrade $http_upgrade;、proxy_set_header Connection "upgrade";
WebSocket 协议本身不处理鉴权,首次连接时无法携带 Cookie 以外的状态;如果要用 Token,得在查询参数里传 ws://host/?token=xxx,服务端从 req.url 解析——但这会暴露在日志和代理中,敏感场景务必走 HTTPS + 后续消息校验。