简体   繁体   中英

Node.js Remote Start and Communication between Servers

I am new to Node.js and also pretty new to server communication. I have tried to find previous answers, but they are often concerned about communication between server and client. I have a different case, so need your considerate helps.

Let's assume a scenario that we have three systems, localhost (ie, laptop) and two cloud servers. I want to code an js app in the localhost that will slice an array of data into two blocks and send them to the cloud servers (block #1 to the server #1 and block #2 to the server #2). Receiving them, two remote servers start to work at the same time . Then, they do the same computation and send their calculation results to each other if they have updated values.

In this scenario, I want to tackle bolded sentences. I believe using the module "socket.io" will be a proper approach to handle this (especially, remote start and communication) but do not have any clear idea in designing codes. In addition, understanding "socket.io" itself is a bit tricky. If you need further specification on the scenario, please comment.

Along with socket.io, check out a module named Faye ( http://faye.jcoglan.com/node.html ). I have been using it for a couple of years and really like it. Faye is a publish subscribe communication scheme which would allow you to extend your scenario to as many clients as you need. To install faye on your system, run the following command:

 npm install -g faye

Now, here is your server code:

var faye = require('faye');

var Server = new faye.NodeAdapter({mount: ('/FayeServer'), timeout: 120});

//now fire the server up on the port 5555
Server.listen(5555);

//subscribe to channel DataChannel
var Subscription = Server.getClient().subscribe("DataChannel", 
    function(dataObject){    console.log(dataObject)    }, 
    function(status) { 
        console.log('Subscription Status: ' + status);
        //send message with two numbers to any client listening to DataChannel
        Server.getClient().publish('/DataChannel', {A:5,B:12});
    });

Now, here is the client code:

var faye = require('faye');

//open client to server
var Client = new faye.Client('http://127.0.0.1:5555/FayeServer');

//now subscribe to the channel DataChannel
Client.subscribe('/DataChannel', function(dataObject)
{
    Client.publish('/DataChannel', {C:(dataObject.A * dataObject.B)};
});

There is a lot more that can be done, but with this basic framework you can stand up server to N client programs that respond to messages from the server.

You will need to replace 127.0.0.1 with your specific URL and use port numbers and channel names more applicable to your specific application.

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