如何保持脚本流式传输,使其不会断开连接?



所以,我使用的是过滤流。不幸的是,每次我打开它,5分钟后它就会关闭,但在这段时间里,它会收到推特。我想做的是让它保持全天候运行,这样它就不会在5分钟后关闭。此外,如果它断开连接,我希望它这样做,它会尝试再次连接。

这是我用来帮助调整代码的代码示例:

  • https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/master/Filtered-Stream/filtered_stream.js

function streamTweets(retryAttempt) {
const stream = needle.get(streamURL, {
headers: {
Authorization: `Bearer ${TOKEN}`
},
retryAttempt: 20000
});
stream.on('data', (data) => {
try {
const json = JSON.parse(data)
console.log(json.data.text)
retryAttempt = 0;
} catch (e) {
if (data.detail === "This stream is currently at the maximum allowed connection limit.") {
console.log(data.detail)
process.exit(1)
} else {
// Keep alive signal received. Do nothing.
}
}
}).on('err', error => {
if (error.code !== 'ECONNRESET') {
console.log(error.code);
process.exit(1);
} else {
// This reconnection logic will attempt to reconnect when a disconnection is detected.
// To avoid rate limits, this logic implements exponential backoff, so the wait time
// will increase if the client cannot reconnect to the stream. 
setTimeout(() => {
console.warn("A connection error occurred. Reconnecting...")
streamTweets(++retryAttempt);
}, 2 ** retryAttempt)
}
});
return stream;
}
(async() => {
let currentRules;
try {
//get all stream rules
currentRules = await getRules();
//delete all stream rules
await deleteRules(currentRules);
//Set rules based on array above
await setRules();
} catch (e) {
console.error(e);
process.exit(1);
}
streamTweets(0);
})();

您是否尝试在标头中发送keepalive?

此外,我更改了授权标头,以匹配您链接的GitHub代码源的语法。

function streamTweets(retryAttempt) {
const stream = needle.get(streamURL, {
headers: {
"authorization": `Bearer ${token}`,
"Connection": "keep-alive"
},
retryAttempt: 20000
});

此外,根据Twitter文档:;如果您想关闭连接,可以在Mac或Windows系统上的命令行工具中按Control-C断开连接,也可以关闭窗口">

你确定它没有因为你关闭了终端会话或被ssh超时之类的东西关闭而断开连接吗?

最新更新