javascript - Socket.io updating multiple times -


i included socket.io in small react application , set of listeners in "componentwillmount," 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 server side, 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 have 1 instance of app open works fine, 2 seems updating twice every second, three, 3 times etc. console.logs show too. think it's because of new connections formed server, i'm not sure how fix it.

still pretty new socket.io, welcomed. thank much!

edit: fixed deleting on connection, how things on socket disconnect?

you creating timer on each incoming connection. required 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--;     }); }); 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -