文档
- 服务端使用: ws: a Node.js WebSocket library
- 客户端使用: WebSocket
服务端
安装依赖
pnpm i ws
修改 package.json
"type": "module",
server.js
import { WebSocketServer } from "ws"; const wss 061; 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
发表评论