Search code examples
node.jswebsocketmessaging

Node.js WebSockets Send Message


I'm trying to come to terms with how WebSockets work in Node.js but I'm having some trouble with sending a message.

I have my WebSocket server configured as follows (index.js)

var ws = require("ws");
var wsserver = new ws.Server ({
   server: httpserver,
   port: 3030
});

wsserver.on (
   "connection", function connection(connection) {
      console.log("connection");
   }
);
wsserver.on (
   "open", function open(open) {
      console.log("open");
   }
);
wsserver.on (
   "message", function message(message) {
      console.log("message");
   }
);

This seems to be working ok because I can establish the connection using

var wscon = new WebSocket("ws://192.168.20.88:3030");

Which then gives me the connection output on the server. If I try to use send though nothing seems to happen and no error messages

wscon.onopen = function(open) {
  wscon.send("test message");
}

I must be missing something but I don't know what


Solution

  • I might have an answer for this but I'm not entirely sure just yet, I'm going to put this here just in case.

    I think the problem is that the message listener is added to the wrong object (the server object), I tried to add the message listener to the connection object passed to the server and it seems to be working but I'm not 100% sure why

    wsserver.on (
       "connection", function connection(connection) {
          console.log("connection");
          connection.on (
             "message", function message(message) {
                console.log("message : " + message);
             }
          );
       }
    );