Gracie williams
Gracie williams

Reputation: 1145

Decoding buffer received from client in websocket

I have simple websocket server and client in node js ,

my server

var WebSocketServer = require("ws").Server;
var wsServer = new WebSocketServer({ port: 5555 });

wsServer.on("connection", function (ws) {
  console.log("Connection established!");
  ws.send("Connection established!");
  ws.on("message", function (msg) {
    ws.send("Got your message!");
    console.log(msg);
    console.log(msg.data);
  });
});

and client looks like below

var ws = new WebSocket("ws://localhost:5555");
function sendMsg() {
 ws.send(document.getElementById("msg").value);
}
ws.onmessage = function(event) {
    console.log(event);
 console.log("server mgs:", event.data);
}
ws.onerror = function(event) {
 console.log("Server err:", event.data);
}

Connections are getting established but the message received is displaying something like below ,instead of actual text that i have sent from client.I am using visual code terminal in mac.

Received: <Buffer 74 65 74>
Received: <Buffer 74 65 74 64 64>

Upvotes: 1

Views: 1104

Answers (1)

Nikita
Nikita

Reputation: 71

Try to use Buffer.toString(). Then your server code would include:

ws.on("message", function (msg) {
   ws.send("Got your message!");
   console.log(msg.toString());
});

Note that the default format is utf8. Check if it fits your needs.

Upvotes: 2

Related Questions