gpt4 book ai didi

javascript - Socket.io 多次更新

转载 作者:行者123 更新时间:2023-12-02 14:24:26 25 4
gpt4 key购买 nike

我将 socket.io 包含在一个小型 React 应用程序中,并在“componentWillMount”中设置了所有监听器,如下所示。

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

当我只打开应用程序的一个实例时,它工作正常,但打开两个实例时,它似乎每秒更新两次,然后是三、三次等等。console.logs 也显示了这一点。我认为这是因为与服务器形成了新的连接,但我不知道如何修复它。

对 socket.io 来说还是很新,所以欢迎任何帮助。太感谢了!

编辑:我通过删除连接来修复它,但是如何在套接字断开连接时执行操作?

最佳答案

您正在为每个传入连接创建一个计时器。只需执行一次此操作。

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

关于javascript - Socket.io 多次更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38406081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com