我正在为我工作的一家托管公司编写状态检查器,我们想知道如果可能的话,我们如何使用 nodejs 检查端口的状态。如果没有,您能否提出任何其他想法,例如使用 PHP 和阅读 STDOUT?
问问题
9755 次
2 回答
24
是的,使用该net
模块很容易做到这一点。这是一个简短的例子。
var net = require('net');
var hosts = [['google.com', 80], ['stackoverflow.com', 80], ['google.com', 444]];
hosts.forEach(function(item) {
var sock = new net.Socket();
sock.setTimeout(2500);
sock.on('connect', function() {
console.log(item[0]+':'+item[1]+' is up.');
sock.destroy();
}).on('error', function(e) {
console.log(item[0]+':'+item[1]+' is down: ' + e.message);
}).on('timeout', function(e) {
console.log(item[0]+':'+item[1]+' is down: timeout');
}).connect(item[1], item[0]);
});
显然可以改进。例如,如果无法解析主机,它当前会中断。
于 2012-05-23T15:52:41.113 回答
0
class ServiceMonitor {
constructor( services){
this.services = services
}
async monitor () {
let status = {
url : {},
alias: {}
}
for ( let service of this.services ) {
let isAlive = await this.ping ( service )
status.url [ `${service.address}:${service.port}` ] = isAlive
status.alias[ service.service ] = isAlive
}
return status
}
ping ( connection ) {
return new Promise ( ( resolve, reject )=>{
const tcpp = require('tcp-ping');
tcpp.ping( connection,( err, data)=> {
let error = data.results [0].err
if ( !error ) {
resolve ( true )
}
if ( error ) {
resolve ( false )
}
});
})
}
}
( async function test () {
let services = [
{
service : "redis_local",
address : "localhost",
port : 6379,
timeout : 1000,
attempts: 1
},
{
service : "redis_prod",
address : "192.168.7.136",
port : 6379,
timeout : 1000,
attempts: 1
},
{
service : "ussd_prod",
address : "192.168.7.136",
port : 1989,
timeout : 1000,
attempts: 1
},
{
service : "fraud_guard_prod",
address : "192.168.7.136",
port : 1900,
timeout : 1000,
attempts: 1
}
],
status = await new ServiceMonitor ( services ).monitor ()
console.log ( status )
}())
返回:
{ url: { 'localhost:6379': true, '192.168.7.136:6379': true, '192.168.7.136:1989': true, '192.168.7.136:1900': true }, alias: { redis_local: true, redis_prod: true, ussd_prod: true, fraud_guard_prod: true } }
于 2019-04-29T10:07:22.200 回答