dnode: Object oriented RPC with Node.js

Node.js has dozen number of library for everything you need to do a network and web application programming. One of old-school style of network or distributed system program is the use of Remote Procedure Call (RPC) mechanism which provided capability for the client to transparently call a function or modify an object inside the server remotely.

There are many choices of RPC server or client (which also works in modern browser) library in Node.js. One which I would try here is called dnode. If you interested, you can try it by installing dnode package from npm via npm -g install dnode command (which will install dnode package globally on your system).

The example here is not-so-simple but has enough explanation for object oriented based RPC (which dealing with modifying some variable inside the server’s object).

dnode-rpc-server.js

var dnode = require('dnode');
var object = {
    a: 0,
    b: 0,
    incA: function(inp) {
        object.a += inp;
    },
    incB: function(inp) {
        object.b += inp;
    },
    getTotal: function(callback) {
        callback(object.a + object.b);
    }
}
var server = dnode(object);

server.listen(5000);

dnode-rpc-client.js

var dnode = require('dnode');

var d = dnode.connect(5000);
d.on('remote', function(remote) {
    remote.incA(1)
    remote.incB(2);
    remote.getTotal(function(result) {
        console.log(result);
        d.end();
    });
});

Afterwards, we can run the server first by node dnode-rpc-server.js & once (and keep it alive), then run node dnode-rpc-client.js many times (to see if the value of A and B still persistent on server side).

$ node dnode-rpc-server.js &
[1] 25537
$ node dnode-rpc-client.js 
3
$ node dnode-rpc-client.js 
6
$ node dnode-rpc-client.js 
9
$

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *