Peter Qiu
Peter Qiu

Reputation: 942

Socket.io updating multiple times

I included socket.io in a small React application and set up all of the listeners in "componentWillMount," as shown below.

componentWillMount() {  
    const socket = io();

    socket.on('update', function(newDataPoint) {
        console.log("Client updating!");
        this.setState({
            count: newDataPoint.count,
            temperature: newDataPoint.temperature,
            humidity: newDataPoint.humidity,
            pressure: newDataPoint.pressure
        }); 
    }.bind(this));      
}

On the server side, I have this:

io.on('connection', function(socket) {
    const pulse = setInterval(function() {
        console.log("From server."); 
        io.emit('update', {
            temperature: Math.floor(Math.random() * 10 + 70),
            count: Math.floor(Math.random() * 300) + 5000, 
            humidity: Math.floor(Math.random() * 5) + 30,
            pressure: Math.floor(Math.random() * 3) + 29
        });
    }, 1000);

    socket.on('disconnect', function() {
        clearInterval(pulse);
    });
});

When I have just one instance of the app open it works fine, but with two it seems to be updating twice every second, then with three, three times etc. The console.logs show this too. I think it's because of new connections formed with the server, but I'm not sure how to fix it.

Still pretty new to socket.io, so any help is welcomed. Thank you so much!

Edit: I fixed it by just deleting on connection, but how would I do things on a socket disconnect?

Upvotes: 0

Views: 739

Answers (1)

thst
thst

Reputation: 4602

You are creating a timer on each incoming connection. It is required to do this only once.

var connected = 0;

const pulse = setInterval(function() {
    console.log("From server."); 
    if(connected > 0) {
        io.emit('update', {
            temperature: Math.floor(Math.random() * 10 + 70),
            count: Math.floor(Math.random() * 300) + 5000, 
            humidity: Math.floor(Math.random() * 5) + 30,
            pressure: Math.floor(Math.random() * 3) + 29
        }
    });

}, 1000);

io.on('connection', function(socket) {
    connected++;
    socket.on('disconnect', function() {
        connected--;
    });
});

Upvotes: 2

Related Questions