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));
}
、私はこれを持っている:私はアプリの1つのインスタンスのみが開いているとき
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);
});
});
は、それが正常に動作しますが、2でそれは二回秒ごとに更新されているようだし、 3回、3回など。console.logにもこれが表示されます。サーバーとの新しい接続が原因だと思いますが、修正方法がわかりません。
まだsocket.ioにはかなり新しいので、どんなヘルプも歓迎されています。どうもありがとうございます!
:接続時に削除するだけで解決しましたが、ソケット切断時にはどうすればいいですか?
サーバ側では 'socket.emit()'を使用しないでください。クライアントが接続するたびにタイマーを作成しているので、クライアントごとに1つのタイマーを追加してデータを送信します。 – thst
すべての接続に同じデータを持たせたい場合は、io.emitを使用しませんか?私はsocket.emitが各ソケットの新しいデータを生成したと思ったが、間違っている可能性がある –
次に接続関数の外にタイマーを作成するか、または2回作成されていないことを確認する必要があります。 – thst