【问题标题】:NodeJS WebSocket Server on 'message' doesn't work\'消息\' 上的 NodeJS WebSocket 服务器不工作
【发布时间】:2023-01-12 18:44:00
【问题描述】:

我正在学习 JS 中的网络套接字并尝试制作最简单的聊天应用程序。我不知道为什么,但是 on message 事件对服务器套接字不起作用。

你能解释一下哪里出了问题吗?

有3个文件:

  • 服务器.js
  • 客户端.js
  • 客户端.html

我用 node 运行 server.js,用 VS Code 实时服务器运行 client.html,所以地址是 http://127.0.0.1:5500/src/client.html

服务器.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}`);
});

客户端.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");
}

客户端.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>

尝试了与其他答案不同的东西。它没有帮助。

【问题讨论】:

    标签: javascript node.js websocket


    【解决方案1】:

    你在哪里

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

    这不是返回客户端对象,而是返回新的 ws 连接,所以试试这个..

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

    【讨论】:

      【解决方案2】:
      wss.on("message", (message) => {
        console.log(`message from client: ${message.data}`);
      });
      

      进去

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

      【讨论】:

        猜你喜欢
        • 2018-09-07
        • 2016-01-06
        • 2020-10-30
        • 1970-01-01
        • 2013-11-12
        • 2019-09-22
        • 2015-06-07
        • 2014-09-08
        • 2011-11-30
        相关资源
        最近更新 更多