【发布时间】: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