Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NodeJS WebSocket Server on 'message' doesn't work

I am learning web socket in JS and trying to make simpliest chat app. I dont know why, but on message event doesn’t work for server socket.

Can you explain whats wrong?

There are 3 files:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • server.js
  • client.js
  • client.html

And I running server.js with node and client.html with VS Code live-server, so the address is http://127.0.0.1:5500/src/client.html

server.js

const WebSocket = require("ws");

const PORT = 9999;

let wss = new WebSocket.Server({ port: PORT });

wss.on("connection", (client) => {
  client.send(`[server] ${new Date()}: hello new client`);
});

wss.on("message", (message) => {
  console.log(`message from client: ${message.data}`);
});

client.js

const client = new WebSocket(`ws://localhost:${9999}`);

client.onopen = () => {
  console.log("[client] connecting...");
};

client.onmessage = (message) => {
  console.log(`${message.data}`);
};

function PING() {
  console.log("[client] sending PING...");
  client.send("PING");
}

client.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <button onclick="PING()">PING</button>

    <script src="./client.js" defer></script>
</body>
</html>

Tried different things from other answers. It didn’t help.

>Solution :

where you have

wss.on("connection", (client) => {
  client.send(`[server] ${new Date()}: hello new client`);
});

This is not returning a client object, it’s returning the new ws connection, so try this..

wss.on("connection", (ws) => {
  ws.send(`[server] ${new Date()}: hello new client`);
  ws.on('message',(msg) => console.log({ msg }));
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading