React客户端使用Socket.io接收两个连接



我正在用SocketIO开发一个简单的应用程序,遇到了这个问题。在服务器中,我有以下代码:

const httpServer = require('http').createServer();
const socketIO = require('socket.io');
const port = process.env.PORT_WS || 5001;
const io = socketIO(httpServer, { cors: { origin: '*' } });
io.on('connection', (socket) => {
console.log('Connected to socket');
socket.on('join-room', () => {
console.log('joined room')
});
});
httpServer.listen(port, () => {
console.log(`Listening on the port ${port}`);
});

在客户端中,我有以下代码:

import { io } from 'socket.io-client';
export default class SocketConnection {
constructor() {
this.initializeSocketConnection();
this.initializeSocketEvents();
}
initializeSocketConnection() {
console.log('I am here');
this.socket = io('ws://localhost:5001');
}
initializeSocketEvents() {
this.socket.on('connect', () => {
console.log('Socket connected');
});
}
}

我在控制台中收到两条Socket connected消息。

这不是重新呈现的问题,因为I am here消息只记录一次。

我在客户端和后端都使用socket.io版本4.0.1

所以之所以会发生这种情况,是因为在React Strict模式中,构造函数会被调用两次。React似乎掩盖了这一点。由于CCD_;关于";事件,React没有办法";隐藏";这因此,'I am here'将被显示一次,而'Socket connected'将被显示两次。

最新更新