Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send message from server to client with dnode

A couple of month ago I discovered nowjs and dnode and finally used nowjs (and https://github.com/Flotype/nowclient) for client / server bidirectional communication.

nowclient enables nowjs communication between 2 node processes (instead of between a node process and a browser for nowjs out of the box). I was then able to send data from the client to the server and from the server to the client. I now use node 0.6.12 and it's kind of painful to use node 0.4.x to run the client.

I'm giving a closer look to dnode and I'm not really sure how the server to client communication is working. Is it possible that the server sends a direct message to the client ? The idea is to have a client to register on the server (at first connection) and enable the server to contact the client when it needs to.

From what I understand, calling a method on the server is possible if the client has requested something from the server at first place. Is that correct ?

like image 874
Luc Avatar asked May 05 '12 12:05

Luc


1 Answers

dnode uses a symmetric protocol so either side can define functions that the opposing side can call. There are 2 basic approaches you can take.

The first way is to define a register function on the server side and to pass in a callback from the client.

server:

var dnode = require('dnode');

dnode(function (remote, conn) {
    this.register = function (cb) {
        // now just call `cb` whenever you like!
        // you can call cb() with whichever arguments you like,
        // including other callbacks!

        setTimeout(function () {
            cb(55);
        }, 1337);
    };
}).listen(5000)

client:

var dnode = require('dnode');

dnode.connect('localhost', 5000, function (remote, conn) {
    remote.register(function (x) {
        console.log('the server called me back with x=' + x);
    });
});

or instead you could directly call the client from the server in a symmetric fashion once the method exchange is complete:

server:

var dnode = require('dnode');

dnode(function (remote, conn) {
    conn.on('ready', function () {
        remote.foo(55);
    });
}).listen(5000);

client:

var dnode = require('dnode');
dnode(function (remote, conn) {
    this.foo = function (n) {
        console.log('the server called me back with n=' + n);
    };
}).connect('localhost', 5000);
like image 84
substack Avatar answered Sep 20 '22 16:09

substack