You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用ws库搭建WebSocket服务端接收消息显示Buffer异常问题

问题原因
  • ws库的message事件默认返回的消息类型为Buffer(二进制数据),直接打印该对象就会输出十六进制格式的Buffer内容,不是你发送的明文文本。
  • 你现有服务端代码中的console.log(msg.data)写法有误:服务端message事件的回调第一个参数就是接收的消息本身,没有.data属性,这行代码执行会输出undefined,无法拿到有效内容。
解决方法

两种常用方案可选:

方案1:手动转换Buffer为字符串

调用Buffer的toString()方法即可按默认UTF-8编码转成明文,修改服务端message事件逻辑:

wsServer.on("connection", function (ws) {
  console.log("Connection established!");
  ws.send("Connection established!");
  ws.on("message", function (msg) {
    ws.send("Got your message!");
    const receiveText = msg.toString();
    console.log(receiveText);
  });
});

方案2:初始化服务时配置直接返回UTF-8字符串

创建WebSocketServer时添加utf8Recv: true配置项,后续message事件会直接返回UTF-8格式的字符串,无需手动转换:

var WebSocketServer = require("ws").Server;
var wsServer = new WebSocketServer({ 
  port: 5555,
  utf8Recv: true
});

wsServer.on("connection", function (ws) {
  console.log("Connection established!");
  ws.send("Connection established!");
  ws.on("message", function (msg) {
    ws.send("Got your message!");
    console.log(msg); // 直接输出明文文本
  });
});

补充注意:客户端和服务端的消息回调参数逻辑不同,不要混淆:客户端ws.onmessage的回调参数是事件对象,需要取.data属性拿到消息内容;服务端ws.on('message')的回调第一个参数就是消息本身,无需额外取属性。

内容的提问来源于stack exchange,提问作者Gracie williams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 20:57:04