Mis*_*pic 3 javascript websocket node.js
我有一个 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);
});
});
Run Code Online (Sandbox Code Playgroud)
message是一个 JSON 对象。日志输出是:
received message from redis: {"temp":81}
message is type object
stringified is type string
Run Code Online (Sandbox Code Playgroud)
在客户端,我有:
socket.onmessage = function(e) {
console.log(e.data)
...
};
Run Code Online (Sandbox Code Playgroud)
日志输出是:
{"type":"Buffer","data":[123,34,116,101,109,112,34,58,53,52,125]}
为什么我没有收到字符串?
如果在服务器上我硬编码:
client.send('foobar');
Run Code Online (Sandbox Code Playgroud)
然后客户端代码将注销:
食物吧
这是因为 Node 中任何类型的基于套接字的通信都基于 Buffers(更准确地说Unit8Array,是一种 TypedArray)。
您可以安全地调用toStringBuffer 来获取字符串,或者使用 Streams 对接收到的数据进行任何类型的所需转换。
编辑:顺便说一句,当您尝试console.log使用 Buffer 时,它的toString方法将被隐式调用。
| 归档时间: |
|
| 查看次数: |
2694 次 |
| 最近记录: |