文档
服务端
安装依赖
pnpm i ws
修改 package.json
"type": "module",
server.js
import { WebSocketServer } from "ws"; const wss = new WebSocketServer({ port: 8080 }); wss.on("connection", function (ws) { // 接收消息 Buffer ws.on("message", function (data) { console.log(data); console.log("received: %s", data); // 返回消息 ws.send(data.toString()); }); // 断开连接 ws.on("close", function () { console.log("close"); }); });
启动服务端
node server.js
客户端
index.html
<script> // 创建一个 WebSocket 连接 const ws = new WebSocket('ws://localhost:8080'); // 监听连接成功 ws.addEventListener('open', function(){ console.log('open'); ws.send('Hello!') }) // 监听返回的消息 ws.addEventListener('message', function(event){ console.log(event.data); }) // 监听断开连接 ws.addEventListener('close', function(event){ console.log('断开连接'); }) </script>