自动检测没有端口号依赖关系的NodeJS应用程序

时间:2017-07-14 07:32:11

标签: node.js npm

我在Node Js中有两个应用程序A和B,而应用程序B想要与应用程序A进行通信。

现在,应用程序A在运行时动态选择其端口。那么应用程序B如何发现运行哪个端口应用程序?

2 个答案:

答案 0 :(得分:0)

您可以在应用程序A和应用程序B中处理 ECONNREFUSED 中的事件,然后在Express中启动服务器,这将处理used中的端口。如果您看到此错误,则只需更改端口号动态地适用于两个应用程序。

答案 1 :(得分:0)

我做了更多的研究,并提出了解决方案“dns-discovery”“openport”

首先使用“openport”检查系统中打开的端口,然后使用“dns-discoverry”

申请A

var op = require('openport');
op.find(
    {
        startingPort: 8050,
        endingPort: 8999
    },
    function (err, port) {
        if (err) { console.log(err); return; }
        console.log('opened port is:::::::::' + port);
        ServerStart(port);
    }
);

function ServerStart(port) {
    var discovery = require('dns-discovery');
    var disc = discovery();
    disc.announce('connect-apps', port, function () {
        console.log("announcement start")
    });
    var io = require('socket.io')(port);

    io.on('connection', function (socket) {
        socket.on('message', function (msg) {
            console.log("Response From Client::::::::::::" + msg);
            socket.send("Congratulations from Server");
        });
        socket.on('disconnect', function (msg) {
            console.log("We are disconnected");
        });
    })
}

申请B

var discovery = require('dns-discovery')
var disc = discovery()
disc.lookup('connect-apps', function () {
    console.log('Server Lookup Started:::::::::::::::::::')
})
disc.on('peer', function (name, peer) {
    console.log("Server found:::::::::" + peer.host + ':::' + peer.port);
    var ws = 'ws://' + peer.host + ':' + peer.port;
    var socket = require('socket.io-client')(ws, { forceNew: true });
    socket.io.opts.transports = ['polling', 'websocket'];
    socket.on('connect', function () {
        console.log('connected');
        socket.send('Hello from Client 1::::::::Vishal Shori Machine');
    });
    socket.on('message', function (msg) {
        console.log("response again::::::::::::" + msg);
    });
    disc.destroy();
})

供参考:

https://www.npmjs.com/package/openport

https://github.com/mafintosh/dns-discovery