Send message from server to client with dnode

A few months ago, I discovered nowjs and dnode and finally used nowjs (and https://github.com/Flotype/nowclient ) for bi-directional communication between client and server.

nowclient enables nowjs communication between 2 node processes (and not between the node process and the browser for nowjs out of the box). Then I was able to send data from the client to the server and from the server to the client. Now I am using node 0.6.12, and it hurts to use node 0.4.x to start the client.

I'll take a closer look at dnode, and I'm not quite sure how the interaction with the server and client works. Is it possible that the server sends a direct message to the client? The idea is that the client can register on the server (on the first connection) and allow the server to access the client when it needs it.

From what I understand, a method call on the server is possible if the client requested something from the server in the first place. It is right?

+6
source share
1 answer

dnode uses a symmetric protocol so that both sides can define functions that the opposite side can call. There are two main approaches you can take.

The first way is to define the registration function on the server side and pass 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 can directly call the client from the server in a symmetric way after the exchange of methods is completed:

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); 
+11
source

Source: https://habr.com/ru/post/914961/


All Articles