【问题标题】:WebSocket always sending stringified JSON object as bufferWebSocket 总是将字符串化的 JSON 对象作为缓冲区发送
【发布时间】:2016-12-26 19:57:08
【问题描述】:

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

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);
    });
});

message 是一个 JSON 对象。日志输出为:

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

在客户端,我有:

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

日志输出为:

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

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

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

client.send('foobar');

然后客户端代码将注销:

foobar

【问题讨论】:

  • 您的整个日志输出可能是 JSON 字符串。在客户端尝试console.log(typeof e.data),看看它是否告诉你它是一个字符串。另外,请让您的问题的标题更有意义。
  • @jfriend00 实际上typeof e.data 是一个字符串。我不清楚我应该如何处理这个。为什么字符串化 JSON 对象和基本字符串之间存在差异?干杯。
  • 我的问题是来自 Redis 的 message 不是字符串,但是当我调用 console.log('received message from redis: ' + message); 时,toString() 被隐式调用。我很懒惰,没有找到合适的检查员,所以console.log 没有向我展示我需要查看的内容。
  • 以后,您可以这样做:console.log('received message from redis: ', message); 而不是 console.log('received message from redis: ' + message);,您将看到整个对象,而不仅仅是 .toString() 转换。

标签: javascript node.js websocket


【解决方案1】:

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

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

编辑:顺便说一句,当你尝试 console.log 一个缓冲区时,它的 toString 方法将被隐式调用。

【讨论】:

  • 看起来这是我的用户错误,但我毫不怀疑您确实是正确的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
  • 2020-06-02
  • 2018-06-27
  • 1970-01-01
  • 2012-09-21
  • 2021-01-04
相关资源
最近更新 更多