【发布时间】: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