【问题标题】:Poor performance with socket.io appsocket.io 应用程序性能不佳
【发布时间】:2018-04-04 09:22:31
【问题描述】:

我正在尝试创建一个 socket.io 应用程序,用户可以在其中选择一种颜色,并为所有用户提供该颜色的元素的背景颜色。我让它工作,但在点击 15 次后它开始滞后,服务器响应数据的时间越来越长。

这可能是因为我使用 react 来实现它吗?我不确定设置组件生命周期的正确方法。

可视化

客户

import React, { Component } from 'react';
import io from 'socket.io-client';
import { SketchPicker } from 'react-color';

class App extends Component {
    constructor() {
        super();
        this.state = {
            background: '#ffffff'
        };

        this.socket = io.connect('http://localhost:5000');
    }

    handleChange = color => {
        this.socket.emit('colorChange', color.hex);
    };

    render() {
        const { background } = this.state;

        this.socket.on('changedColor', data => {
            this.setState({ background: data.color });
        });

        return (
            <div className="app" style={{ backgroundColor: background }}>
                <h1>Choose a color!</h1>
                <SketchPicker onChangeComplete={this.handleChange} color={background} />
            </div>
        );
    }
}

export default App;

(后端)服务器

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
// Port enviroment
const PORT = process.env.PORT || 5000;

app.use(express.static(__dirname + '/node_modules'));

app.get('/', (req, res, next) => {
  res.sendFile(__dirname + '/client/public');
});

server.listen(PORT, () => console.log(`Hey the server is online at port: ${PORT}`))

io.on('connection', (socket) => {
  console.log(`Socket connection: ${socket.id}`);

  socket.on('colorChange', (color) => {
    console.log(`The color: ${color} was sent from: ${socket.id}`);
    const colorMeta = {
      user: socket.id,
      color: color
    }
    io.sockets.emit('changedColor', colorMeta);
  });

  socket.on('disconnect', () => {
    console.log('Hey the IO server disconnected!');
  });

});

【问题讨论】:

    标签: node.js reactjs socket.io


    【解决方案1】:

    不要在render 调用中绑定事件监听器。 React 设置为能够在需要时调用render,因此它可以将渲染的组件输出与先前存在的 DOM 进行比较。每次它调用渲染时,您都在为您的套接字创建 另一个 事件侦听器。

    由于您的套接字具有较长的使用寿命,您将在其上收集大量事件侦听器。这些事件侦听器中的每一个都将调用setState,这可能会导致重新渲染并附加更多的事件侦听器。

    您需要在构造函数或componentDidMount 中绑定该事件侦听器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 2020-07-17
      • 2021-06-30
      相关资源
      最近更新 更多