简体   繁体   English

Node.js:两台服务器之间的通信(网络)

[英]Node.js : Communication between two servers (net)

I need help about the communication between two servers using 'net' library. 我需要帮助使用'net'库在两台服务器之间进行通信。 I have two servers process : a master and a slave. 我有两个服务器进程:主服务器和从服务器。 The goal is : when the master server down, the slave get up and continue the job. 目标是:当主服务器关闭时,从服务器启动并继续工作。

Well, this is my code : 嗯,这是我的代码:

    // MASTER
    var server = net.createServer(function (conn) {
        conn.on("error", function() {
        });
    });
    server.listen(61337, "localhost", function () {});

    // SLAVE
    var socket = new net.Socket();
    socket.connect(61337, "localhost", function () {
    });
    socket.on('error', function (exc) {
        if((""+exc) == "Error: read ECONNRESET") {
            console.log("ALERT : MASTER is down !");
        }
    });

How can i do to send a message MASTER -> SLAVE ? 如何发送消息MASTER - > SLAVE?

Thanks. 谢谢。

You can use the cluster module ( https://nodejs.org/api/cluster.html ) to create a master-slave logic. 您可以使用群集模块( https://nodejs.org/api/cluster.html )创建主从逻辑。

Basically your first process should be the master and the child(ren) could be the slave(s); 基本上你的第一个过程应该是主人,孩子可以是奴隶; then children could for example ask the master his status every minutes; 那么孩子们可以每分钟向主人询问他的状态; If this one does not reply, it means the master process is down and at that moment you can do any logic you would like to. 如果这个没有回复,则表示主进程已关闭,此时您可以执行任何您想要的逻辑。

You can use worker.send(msg) and process.send(msg) and make them respectively listen the message event to deal with response. 您可以使用worker.send(msg)process.send(msg)并使它们分别监听message事件以处理响应。

process|worker.on('message', function(msg) {
    // Code logic
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM