Home > front end >  NodeJS WebSocket Server on 'message' doesn't work
NodeJS WebSocket Server on 'message' doesn't work

Time:01-13

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:

  • 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.

CodePudding user response:

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

CodePudding user response:

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

goes within

wss.on("connection", (client) => {
  client.send(`[server] ${new Date()}: hello new client`);
  client.on("message", (message) => {
    console.log(`message from client: ${message.data}`);
  });
});
  • Related