WebSocket总是将字符串化的JSON对象作为缓冲区发送

时间:2016-12-26 19:57:08

标签: javascript node.js websocket

我有一个节点/ ws WebSocket服务器在Redis背板上侦听消息,然后将其转发给正在侦听的任何客户端:

__str__

sub.on("message", function(channel, message) { console.log('received message from redis: ' + message); console.log('message is type ' + typeof(message)); var stringified = JSON.stringify(message); console.log('stringified is type ' + typeof(stringified)); wss.clients.forEach(function each(client) { client.send(stringified); }); }); 是一个JSON对象。日志输出为:

message

在客户端,我有:

received message from redis: {"temp":81}
message is type object
stringified is type string

日志输出为:

  

{"类型":"缓冲液""数据":[123,34,116,101,109,112,34,58,53,52,125]}

为什么我没有收到字符串?

如果在服务器上我硬编码:

socket.onmessage = function(e) {
  console.log(e.data)
  ...
};

然后客户端代码将注销:

  

foobar的

1 个答案:

答案 0 :(得分:2)

这是因为Node中任何类型的基于套接字的通信都基于Buffers(更准确地说,基于Unit8Array,一种TypedArray)。

您可以安全地在缓冲区上调用toString来获取字符串,或使用Streams对接收到的数据进行任何类型的转换。

编辑: BTW,当您尝试console.log缓冲区时,将隐式调用toString方法。