[英]Events for network status change in Node.js?
我找到的所有解决方案都只是轮询服务。 例如,他们每秒 ping google.com
以查看 Node 服务是否可以访问 Internet。
但是,我正在寻找一个更干净的基于事件的解决方案。 在浏览器中,有window.ononline
和window.onoffline
。 我知道这些并不完美,但它们总比没有好。
我不一定要寻找一种方法来查看 Node 服务是否在线,我只是在寻找一种方法来查看操作系统是否认为它在线。 例如,如果操作系统没有连接到任何网络接口,那么它肯定是离线的。 但是,如果它连接到路由器,那么我也许可以 ping google.com
。
我相信目前,这是判断您是否已连接的最有效方法。
如果你想要一个“基于事件”的解决方案,你可以用这样的东西包装轮询服务:
connectivity-checker.js
const isOnline = require("is-online");
function ConnectivityChecker (callback, interval) {
this.status = false;
this.callback = callback;
this.interval = this.interval;
// Determines if the check should check on the next interval
this.shouldCheckOnNextInterval = true;
}
ConnectivityChecker.prototype.init = function () {
this.cleanUp();
this.timer = setInterval(function () {
if (this.shouldCheck) {
isOnline().then(function (status) {
if (this.status !== status) {
this.status = status;
this.callback(status);
this.shouldCheckOnNextInterval = true;
}
}).catch(err => {
console.error(err);
this.shouldCheckOnNextInterval = true;
})
// Disable 'shouldCheckOnNextInterval' if current check has not resolved within the interval time
this.shouldCheckOnNextInterval = false;
}
}, this.interval);
}
ConnectivityChecker.prototype.cleanUp = function () {
if (this.timer) clearInterval(this.timer);
}
export { ConnectivityChecker };
然后在您的使用站点(例如app.js
)
app.js
const { ConnectivityChecker } = require("/path/to/connectivity-checker.js");
const checker = new ConnectivityChecker(function(isOnline) {
// Will be called ONLY IF isOnline changes from 'false' to 'true' or from 'true' to 'false'.
// Will be not called anytime isOnline status remains the same from between each check
// This simulates the event-based nature you're looking for
if (isOnline) {
// Do stuff if online
} else {
// Do stuff if offline
}
}, 5000);
// Where your app starts, call
checker.init();
// Where your app ends, call
// checker.cleanUp();
希望这可以帮助...
你的假设部分正确。 从操作系统层面,您可以检测您是否连接到网络,但这并不能保证您可以访问互联网。 此外,对于不同的操作系统,本机检查我是否有网络连接也会有所不同。
因此,了解您是否具有 Internet 连接的最可靠方法是尝试从 Internet 访问任何资源,然后查看是否成功。 由于某些原因,资源可能无法访问,因此您的策略应该是访问多个知名资源,看看您是否可以访问其中的任何一个。
为此,我使用了is-online npm 包。 它依赖于访问互联网资源和 DNS 解析来检查您是否连接到互联网。
示例代码:
const isOnline = require('is-online');
isOnline().then(online => {
if(online){
console.log("Connected to internet");
}else{
console.log("Not connected to internet");
}
});
** 更新
我认为这个模块有你正在寻找的东西,它有许多使用网络接口的有用方法。
https://www.npmjs.com/package/network
基本示例:告诉您是否已连接到网关,并返回其 IP。
*(我在我的机器上测试过)
var network = require("network");
network.get_gateway_ip(function(err, ip) {
if (err) {
console.log("No Gateway IP found!");
} else {
console.log(`Gateway IP: ${ip}`);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.