我试图让一个非常简单的WebSocket服务器工作,但由于某种原因,我的浏览器无法建立连接。当我加载我的HTML页面时,我得到以下错误
error:index.html:9 WebSocket connection to 'ws://localhost:8080/?chatId=15432' failed:
下面是我的服务器的外观:
const http = require("http");
const WebSocketServer = require("websocket").server;
const server = http.createServer((req, res) => {});
const websocket = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false,
});
const chats = new Map();
websocket.on("request", (request) => {
let connection = request.accept(null, request.origin);
console.log(connection);
console.log(new Date() + " Connection accepted.");
let chatId = request.resourceURL.query.chatId;
if (!chats.has(chatId)) {
chats.set(chatId, []);
}
chats.get(chatId).push(connection);
connection.on("message", (message) => {
console.log("Received Message: " + message.utf8Data);
let chatConnections = chats.get(chatId);
chatConnections.forEach((chatConnection) => {
if (chatConnection !== connection) {
chatConnection.sendUTF(message.utf8Data);
console.log(connection);
}
});
});
connection.on("close", (reasonCode, description) => {
console.log(
new Date() + " Peer " + connection.remoteAddress + " disconnected."
);
let chatConnections = chats.get(chatId);
chatConnections.splice(chatConnections.indexOf(connection), 1);
if (chatConnections.length === 0) {
chats.delete(chatId);
}
});
});
server.listen(8080, "localhost", () => {
console.log("listening on port 8080");
});
下面是我的客户端的外观(即我在浏览器中打开的html文件):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script>
let webSocket = new WebSocket("ws://localhost:8080?chatId=15432", null);
webSocket.onopen = (event) => {
webSocket.send("Hey guys, here's my first message");
console.log("Connection Opened Client");
};
webSocket.onclose = function () {
console.log("WebSocket connection closed.");
};
</script>
</head>
<body></body>
</html>
我期望连接发生并从客户端接收消息,但是由于某种原因没有发生。我错过了一些明显的东西吗?
1条答案
按热度按时间sr4lhrrt1#
onRequest
的用法似乎是核心问题,应该使用websocket.on('connection' ...
方法:大概是这样的
考虑一下我最近写的可以派生和使用的this barebones Websockets chat implementation。它使用的是React 17,但应该可以与React 18一起工作。一旦WSS准备好了,它就会让客户端知道,并开始通信-然后看到乒乓通信。组件的分数和会话命名是任意的。