几个月前,我发现了 nowjs 和 dnode,并最终使用 nowjs(和 https://github.com/Flotype/nowclient)进行客户端/服务器双向通信。
nowclient 启用 2 个 Node 进程之间的 nowjs 通信(而不是开箱即用的 Node 进程和浏览器之间的 nowjs)。然后我就能够将数据从客户端发送到服务器,然后从服务器发送到客户端。我现在使用 Node 0.6.12,使用 Node 0.4.x 运行客户端有点痛苦。
我正在仔细研究 dnode,我不太确定服务器到客户端的通信是如何工作的。服务器是否可能向客户端发送直接消息?这个想法是让客户端在服务器上注册(在第一次连接时)并使服务器能够在需要时联系客户端。
据我了解,如果客户端首先从服务器请求某些内容,则可以调用服务器上的方法。对吗?
最佳答案
dnode 使用对称协议(protocol),因此任何一方都可以定义对方可以调用的函数。您可以采用两种基本方法。
第一种方式是在服务端定义一个注册函数,然后从客户端传入一个回调。
服务器:
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);
关于javascript - 使用 dnode 从服务器向客户端发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10461824/