NodeJS ping端口

时间:2012-05-23 15:40:29

标签: node.js

我正在为我工​​作的托管公司编写状态检查器,我们想知道如果可能的话我们如何使用nodejs检查端口的状态。如果没有,你能否提出任何其他想法,如使用PHP和阅读STDOUT?

2 个答案:

答案 0 :(得分:9)

是的,使用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]);
});

显然它可以改进。例如,如果无法解析主机,它当前会中断。

答案 1 :(得分: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 } }