提问人:Momen Khaled 提问时间:10/19/2023 最后编辑:Momen Khaled 更新时间:10/19/2023 访问量:27
客户端 WebSocket 连接失败
Client Side WebSocket connection, fails
问:
我正在开发 ReactJS 聊天应用程序 当我尝试连接到节点服务器时,我在控制台中收到连接失败的错误
这是客户端应用This is the Client side app
import { Component } from 'react';
import ReactDOM from 'react-dom';
import { w3cwebsocket as W3CWebSocket } from 'websocket';
const client = new W3CWebSocket('ws://127.0.0.1:8000');
export default class App extends Component {
onButtonClick(message) {
client.send(
JSON.stringify({
type: 'message',
msg: message,
})
);
}
componentDidMount() {
client.onopen = () => {
console.log('WebSocket Client Connected');
};
client.onmessage = message => {
const dataFromServer = JSON.parse(message.data);
console.log('Got Reply : ' + dataFromServer);
};
}
render() {
return (
<div>
<button
onClick={() => {
this.onButtonClick('Hello');
}}
>
Send Message
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
这是我遇到的错误
这是服务器端应用程序
const webSocketServerPort = 8000;
const webSocketServer = require("websocket").server;
const http = require("http");
const server = http.createServer();
server.listen(webSocketServerPort, () => {
console.log(`WebSocket server is running on port ${webSocketServerPort}`);
});
const wsServer = new webSocketServer({
httpServer: server,
});
const clients = {};
function getUniqueID() {
return Math.floor(Math.random() * 1000000);
}
wsServer.on("request", (request) => {
var userID = getUniqueID();
console.log(
new Date() +
" Recieved a new connection from origin " +
request.origin +
"."
);
const connection = request.accept(null, request.origin);
clients[userID] = connection;
console.log(
"connected: " + userID + " in " + Object.getOwnPropertyNames(clients)
);
connection.on("message", (message) => {
if (message.type === "utf8") {
console.log("Recieved Message: " + message.utf8Data);
for (key in clients) {
clients[key].sendUTF(message.utf8Data);
console.log("sent Message to: " + clients[key]);
}
}
});
});
根据我遵循的教程,它应该连接成功,但我不知道问题出在哪里
答: 暂无答案
评论