简体   繁体   中英

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM