[英]How to break setinterval in io sockets - Nodejs
有一个API发送一些json数据.nodejs服务器每5秒钟获取一次json数据并通过websocket发送给客户端。如果在clent连接的情况下连接正常,但在客户端断开连接时,连接不会停止。
编码
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");
})
要么
除了websocket之外,您还有其他建议将此json数据发送到客户端吗?
提前感谢您的支持
您的问题是范围问题。 在声明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();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.