NodeJS检测端口是否开放

13

我正在为我所工作的托管公司编写状态检查器,我们想知道如何使用nodejs检查端口的状态是否可行。如果不行,您能否建议其他想法,例如使用PHP并读取STDOUT?

2个回答

26

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

显然这可以得到改进。例如,目前如果无法解析主机,它就会出错。


有人知道如何使用回调函数来返回多个服务器的状态吗? - richardwhitney

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 } }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接