node.js: ws服务端和WebSocket客户端交互示例

文档

  • 服务端使用: ws: a Node.js WebSocket library
  • 客户端使用: WebSocket

服务端

安装依赖

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 &#061; 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>