2016-07-15 3 views
0

작은 React 응용 프로그램에 socket.io를 포함 시켰고 아래와 같이 "componentWillMount"에 모든 수신기를 설정했습니다. 서버 측에 여러 번 업데이트하는 Socket.io

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));  
} 

,이 있습니다

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); 
    }); 
}); 

내가 응용 프로그램의 한 인스턴스가 잘 작동 열이 있지만 두 사람과 함께 그 다음, 매 초마다 두 번 갱신 할 것으로 보인다 3, 3 번 등. console.logs도 이것을 보여줍니다. 나는 그것이 서버와 형성된 새로운 연결 때문이라고 생각하지만, 어떻게 고쳐야할지 모르겠습니다.

아직 socket.io에 새롭지 않아 어떤 도움도 환영합니다. 정말 고맙습니다!

: 수정시 연결을 삭제하면 해결되지만 소켓 연결을 끊으면 어떻게됩니까?

+0

서버 측에서 'socket.emit()'을 사용하지 않아야합니까? 클라이언트가 연결될 때마다 타이머를 생성하므로 한 번 더 타이머를 사용하여 각 클라이언트에 대한 데이터를 방출합니다 .4 – thst

+0

모든 연결에서 동일한 데이터를 갖기를 원한다면 io.emit이 아닌가? socket.emit이 각 소켓에 대해 새로운 데이터를 생성했다고 생각했지만 잘못된 것일 수도 있습니다. –

+0

그러면 연결 함수 외부에서 타이머를 생성하거나 두 번 생성되지 않도록해야합니다. – thst

답변

1

수신 연결마다 타이머가 생성됩니다. 이 작업은 한 번만 수행해야합니다.

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--; 
    }); 
}); 
관련 문제