WebSocket数据不能从缓冲区转换为数组
我只是将数组从客户端发送到服务器。当我尝试从客户端登录此数组时,它会在数组中为我提供随机值。
客户端代码
let ws = new WebSocket("ws://localhost:4000");
ws.send([1,2,3]);
服务器端代码
wss.on("connection", (ws) => {
ws.on("message", m => {
//I searched a little and learnt a way to convert buffer to array with a simple ES6 feature but it doesn't work properly
console.log([...m]);
});
});
输出为:[49、44、50、44、51]
请发布如何修复它,并解释其原因,以便我和其他人可以理解其背后的逻辑。
I simply send an array from client to server. When I try to log this array from the client-side it gives me random values in the array.
Client-Side Code
let ws = new WebSocket("ws://localhost:4000");
ws.send([1,2,3]);
Server-Side Code
wss.on("connection", (ws) => {
ws.on("message", m => {
//I searched a little and learnt a way to convert buffer to array with a simple ES6 feature but it doesn't work properly
console.log([...m]);
});
});
The output is: [ 49, 44, 50, 44, 51 ]
Please post how can I fix it, and explain the reason for it so I and other people can understand the logic behind it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用
JSON.PARSE(M)
将缓冲区解析到JavaScript对象中。请注意,如果消息不是JSON字符串,则会丢失错误。
try parsing the buffer into a javascript object using
JSON.parse(m)
is not required.Please note that if the message is not a JSON string, this will throw an error.
我仍然不知道为什么会发生,但是知道我解决了这个问题。我只是简单地将数组转换为客户端上的字符串,然后将其重新将其重新连接到服务器端的数组。
客户端
服务器端
I still don't know why it happens but know I got a workaround for this problem. I'm simply converting the array to a string on the client-side and reconverting it to an array on the server side.
Client-Side
Server Side