0

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.

2 Answers 2

2

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 }));
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that worked. But can you explain what that means ws.on('message'... if I already have onmessage function in client.js?
This is the on message handing for the Server, the client has only to deal with on ws connection, so can send and receive messages directly, on the Server there are maybe many 1,000's. So you need to listen for a message on each new ws as it connects.
0
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}`);
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.