Node.js: communication between two servers (net)

I need help communicating between two servers using the net library. I have two servers: master and slave. The goal is that when the master is down, the slave will get up and resume.

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?

Thank.

+3


source to share


1 answer


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

Basically your first process should be the master and child (ren) can be the slave (s); then the children could, for example, ask the owner for their status every minute; If this one doesn't respond, it means that the master process is down, at which point you can do whatever logic you would like.



You can use worker.send(msg)

and process.send(msg)

and accordingly listen message

for an event to respond to it.

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

      

0


source







All Articles