【问题标题】:React client receives two connections using Socket.ioReact 客户端使用 Socket.io 接收两个连接
【发布时间】: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


【解决方案1】:

之所以会这样,是因为在 React Strict Mode 中,构造函数被调用了两次。 React 似乎隐藏了这一点。由于console.log('Socket connected'); 在“on”事件中,React 无法“隐藏”它。因此,'I am here' 将显示一次,而'Socket connected' 将显示两次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    相关资源
    最近更新 更多