Как сломать setinterval в io сокетах - Nodejs
Существует API, который отправляет некоторые данные json. Сервер nodejs получает эти данные json и отправляет клиенту веб-сокет каждые 5 секунд. Если подключение включено, когда подключается соединяющее устройство, оно работает, но когда клиент отключается, он не останавливается.
Код
io.on('connection', function(client) {
var loop=setInterval(()=>{
console.log('Client connected...');
fetch('https://www.foo.com/api/v2/searchAssets')
.then(res => res.json())
.then(json =>
{client.emit('news'{json});console.log(json)}),5000);
})});
io.on('disconnetion',function(){
clearInterval(loop);
console.log("disconnected");
})
ИЛИ ЖЕ
Есть ли у вас какие-либо другие советы по отправке этих данных JSON на стороне клиента, кроме веб-сокета?
Заранее спасибо за вашу поддержку
1 ответ
Ваша проблема - это проблема масштаба. Когда вы объявляете loop
вар, это локально для обратного вызова on connection
событие и не существует в on disconnect
событие. Основываясь на документе о том, как обрабатывать разъединение, вы можете переместить обработчик разъединения внутри обработчика соединения следующим образом:
io.on('connection', function(client) {
// Start the interval
var loop = setInterval(()=>{
console.log('Client connected...');
fetch('https://www.foo.com/api/v2/searchAssets')
.then(res => res.json())
.then(json => {
client.emit('news'{json});console.log(json)
} ,5000);
});
// Handles disconnection inside the on connection event
// Note this is using `client.on`, not `io.on`, and that
// your original code was missing the "c" in "disconnect"
client.on('disconnect', () => {
clearInterval(loop);
console.log("disconnected");
});
});
Но я бы не рекомендовал эту архитектуру, поскольку потоковые данные не зависят от клиента. Данные могут быть получены один раз и переданы всем. Вот как вы можете это сделать:
var loop
// The function startStreaming starts streaming data to all the users
function startStreaming() {
loop = setInterval(() => {
fetch('https://www.foo.com/api/v2/searchAssets')
.then(res => res.json())
.then(json => {
// The emit function of io is used to broadcast a message to
// all the connected users
io.emit('news', {json});
console.log(json);
} ,5000);
});
}
// The function stopStreaming stops streaming data to all the users
function stopStreaming() {
clearInterval(loop);
}
io.on('connection',function() {
console.log("Client connected");
// On connection we check if this is the first client to connect
// If it is, the interval is started
if (io.sockets.clients().length === 1) {
startStreaming();
}
});
io.on('disconnetion',function() {
console.log("disconnected");
// On disconnection we check the number of connected users
// If there is none, the interval is stopped
if (io.sockets.clients().length === 0) {
stopStreaming();
}
});