Introduction to the implementation principle of RPC (remote Procedure call) in Node.js

Source: Internet
Author: User
Tags json unique id

Use examples:

The code is as follows:

Service side

var light_rpc = require ('./index.js ');

var port = 5556;

var rpc = new Light_rpc ({

Combine:function (A, B, callback) {

Callback (a + B);

},

Multiply:function (T, CB) {

CB (T*2);

}

}). Listen (port);

Sample Client:

The code is as follows:

Client

Rpc.connect (5556, ' localhost ', function (remote, conn) {

Remote.combine (1, 2, function (res) {

if (res!= 3) {

Console.log (' ERROR ', res);

}

});

});

Simply speaking, the whole process:

1.server-side startup programs, listening ports, implementing functions provided to client invocations (such as the combine and multiply of the above examples), stored in an object.

2.client-side launcher, connecting the server, sending the describe command when the connection is complete, and asking the server to return the function name it can provide the call.

The code is as follows:

Connection.on (' Connect ', function () {

Connection.write (Command (descrcmd));

});

3.server received the describe command, the function name can be used to package the call to send out ("combine", "multiply")

The 4.client terminal receives the function name sent by the server, registers it in its own object, wraps a method for each function name, and makes the local call to the function to actually send the request to the server side:

The code is as follows:

For (var p in Cmd.data) {

REMOTEOBJ[P] = Getremotecallfunction (p, self.callbacks, connection);

The realization of getremotecallfunction see below

}

5.client-side functions that call server-side:

1 generates a unique ID for the incoming callback function, called a callbackid, that is recorded in one of the client's objects.

2 Package The following data sent to the server side: Call Function name, JSON serialized parameter list, Callbackid

The code is as follows:

function Getremotecallfunction (cmdName, callbacks, connection) {

return function () {

var id = uuid.generate ();

if (typeof arguments[arguments.length-1] = = ' function ') {

Callbacks[id] = arguments[arguments.length-1];

}

var args = Parseargumentstoarray.call (this, arguments);

var newcmd = command (CmdName, {id:id, args:args});

Connection.write (Newcmd);

}

}

The 6.server terminal receives the above information, parses the data, deserializes the parameter list, and invokes the function according to the functions name and parameters.

The code is as follows:

var args = Cmd.data.args;

Args.push (Getsendcommandbackfunction (c, cmd.data.id));

Self.wrapper[cmd.command].apply ({}, args);

7. After the function is finished, serialize the result, and send it back to the client side, together with the Callbackid received.

The code is as follows:

function getsendcommandbackfunction (connection, cmdId) {

return function () {

var Innerargs = Parseargumentstoarray.call ({}, arguments);

var resultcommand = command (Resultcmd, {id:cmdid, args:innerargs});

Connection.write (Resultcommand);

};

}

The 8.client terminal receives the function result and Callbackid, takes out the callback function according to the Callbackid, and executes the running result in the callback function.

9. The whole process is complete, see source code: HTTPS://GITHUB.COM/ROMULKA/NODEJS-LIGHT_RPC

Several points of attention:

1. Throughout the process, client and server remain connected, unlike the HTTP protocol sent and received the end of the link, so can not be a broken link to judge the transmission of data once completed. To determine the completion of data reception, the data sent by client and server follows a simple protocol: the length and delimiter of the packet before the data, such as the n:[packet length n data, so that the length of the packet is removed first after the data is received, And then constantly judge whether the accumulated packets are equal to or exceeding this length, if the data transfer is completed, you can begin to parse the extracted data.

2. This RPC is simply not taking into account the type of function in the parameter, such as a parameter is an object, the object has function members, JSON serialization will ignore the function, on the server side can not perform this function.

To solve this problem, there is a need for complex processing:

1. Depth traverse each parameter to be sent to the remote, extract the function member, generate a unique ID for the function, place it in a local object, replace the function member with this ID string, and identify that the member is actually a function. So that the object can be serialized and sent out.

2.server receive the call, when you want to use the function in the Parameter object, you can judge that this is a client-processed function with an ID, send this ID back to the client, and pass the callback function ID to the client in the same way. Wait for the client-side callback.

3.client receives this function ID, finds this function entity, calls, completes, sends back to the server end according to the server-side callback ID

The 4.server end receives the result, finds the callback function, continues execution, completes.

The method of recording a function can be done in other ways, and the general idea is to replace the function with something serializable, and record the function so that it can be found locally when the remote port is invoked. You can refer to the implementation of Dnode.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.