【发布时间】:2021-05-05 03:10:57
【问题描述】:
我正在使用 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。
【问题讨论】:
-
嗨,您从服务器控制台看到多少次显示“已连接到套接字”?
-
@halilcakar 我发布了自己的答案。那是因为我处于严格模式。
标签: node.js reactjs websocket socket.io