首页 > 解决方案 > Handling continuous stream of logs using socket-io in react

问题描述

I am relatively new to sockets, I am working on a react project where user should be able to see the logs during the deployment kinda like the Jenkins build logs. I can't share the exact code but the code looks more or less like the below code.

import socketIOClient from 'socket.io-client';

class ShowLog extends Component{
    constructor(props) {
        super(props);
        this.state = {
            stateLogs: []
        };
        this.socketLogs = [];
    }
    
    // Ignoring the componentDidMount and other unnecessary stuff
    

    // this function will establish the socketio connection
    streamLog = (socketId, url) => {
        this.clientSocket = socketIOClient(url);
        this.clientSocket.on('connect', () => {
            this.clientSocket.emit('join', socketId);
        });
        
        this.clientSocket.on('data', this.handleLogs);
        // error handling here
    }
    
    handleLogs = (data) {
        if(data.length){ // I will be getting messages as an array of strings
            this.socketLogs.push(...data);
            this.setLogs(this.socketLogs); // calling another method to update state
        }
    }
    
    // used throttle with 100ms to create jenkins like log instead of pushing them all at once.
    setLogs = throttle((data) => { 
        this.setState({ stateLogs: data });
    }, 100);
    
    render() {
        const { stateLogs } = this.state;
        return (
            <>
            // other logic here.
            {
                stateLogs.map(message => <li key={message}>{message}</li>)
            }
            </>
        )
    }
}

In my case I will be getting at least 10 messages each second. Also I am using throttle to reduce number of renders for smooth flow of logs.

The problem here is that when the backend is pushing the logs, the logs are getting updated after 2-5 seconds from front end.

Can anyone please give your suggestions on improving the code to reduce the delay that I have mentioned above.

标签: reactjswebsocketsocket.iostreamingdelay

解决方案


推荐阅读