使用dnode从服务器发送消息到客户端

几个月前,我发现了nowjs和dnode,最后使用nowjs(和https://github.com/Flotype/nowclient )进行客户/服务器双向通信。

nowclient支持2个节点进程之间的nowjs通信(而不是节点进程和浏览器之间的nowjs开箱即用)。 然后,我可以将数据从客户端发送到服务器,从服务器发送到客户端。 我现在使用节点0.6.12,使用节点0.4.x来运行客户端是很痛苦的。

我正在仔细研究dnode,而且我不确定服务器到客户端的通信是如何工作的。 服务器是否可能向客户端发送直接消息? 这个想法是有一个客户端在服务器上注册(在第一次连接),并使服务器在需要时联系客户端。

据我所知,在服务器上调用一个方法是可能的,如果客户端首先从服务器请求一些东西。 那是对的吗 ?

dnode使用对称协议,所以任何一方都可以定义对方可以调用的函数。 你可以采取两种基本的方法。

第一种方法是在服务器端定义一个注册函数,并从客户端传入一个callback函数。

服务器:

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) 

客户:

 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); }); }); 

或者一旦方法交换完成,您可以直接从服务器以对称方式调用客户端:

服务器:

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

客户:

 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);