简体   繁体   中英

Node.js : Communication between two servers (net)

I need help about the communication between two servers using 'net' library. 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 ?

Thanks.

You can use the cluster module ( https://nodejs.org/api/cluster.html ) to create a master-slave logic.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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