WebSocket数据不能从缓冲区转换为数组

发布于 2025-01-25 06:19:57 字数 680 浏览 7 评论 0原文

我只是将数组从客户端发送到服务器。当我尝试从客户端登录此数组时,它会在数组中为我提供随机值。

客户端代码

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不奢求什么 2025-02-01 06:19:57

尝试使用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.

乖乖兔^ω^ 2025-02-01 06:19:57

我仍然不知道为什么会发生,但是知道我解决了这个问题。我只是简单地将数组转换为客户端上的字符串,然后将其重新将其重新连接到服务器端的数组。

客户端

ws.send([1,2,3].toString());

服务器端

arr = []

wss.on("connection", (ws) => {
    ws.on("message", m => {
        arr = m.toString().split(",");
        arr = arr.map(x => {
            return parseInt(x);
        });
        console.log(arr);
    });
});

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

ws.send([1,2,3].toString());

Server Side

arr = []

wss.on("connection", (ws) => {
    ws.on("message", m => {
        arr = m.toString().split(",");
        arr = arr.map(x => {
            return parseInt(x);
        });
        console.log(arr);
    });
});

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文