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