dnode 使用对称协议,因此任何一方都可以定义对方可以调用的函数。您可以采取两种基本方法。
第一种方法是在服务器端定义一个注册函数,并从客户端传入一个回调。
服务器:
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);