I'm testing websocket connection. I want to send JSON object from client to Server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({port: 8082});
wss.on("connection", (ws) => {
console.log('server is connected');
ws.on("message", (mesg) => {
const a = mesg.toString();
console.log(a);
});
ws.on("close", () => {
console.log("Client has disconnected!");
});
});
On the server side:
console.log(mesg)
returns <Buffer>
console.log(a)
returns object Object]
JSON.parse(a)
throws error message.
I'm at a loss. What am I doing wrong? Thank you!
CodePudding user response:
Problem is on the client side. You're not serializing your JSON when sending it over the socket.
Add a call to JSON.stringify()
on the client before sending, and it should work.
On the server then it's just a matter of using JSON.parse(mesg.toString())
to output the buffer to a string and deserialize the JSON back to an object.