WebSocket 是 HTML5 中的协议,支持持久连续,HTTP 协议不支持持久性连接。HTTP1.0 和 HTTP1.1 都不支持持久性的链接,HTTP1.1 中 的keep-alive,是将多个 HTTP 请求合并为 1 个
const ws = new WebSocket('ws:localhost:8000')
ws.addEventListener('open', handleOpen, false);
ws.addEventListener('close', handleClose, false);
ws.addEventListener('error', handleClose, false);
ws.addEventListener('message', handleMessage, false);
handleMessage(e) { const msgData = JSON.prase(e.data) }
ws.send(JSON.stringify({}));
const Ws = require('ws');
const server = new Ws.Server({ port: 8000 })
server.on('open', handleOpen);
server.on('close', handleClose);
server.on('error', handleError);
server.on('connection', handleConnection);
前端连接上来后:
handleConnection(ws) { ws.on('message', handleMessage) }
handleMessage(data, isBinary) { server.clients.forEach(c => c.send(data, { binary: isBinary }) ) }
npm install vite
package.json: