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

Send message from server to client with dnode

本文关键字:客户端 服务器 dnode 使用      更新时间:2023-09-26

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

nowClient 在 2 个节点进程之间启用 nowJS 通信(而不是在节点进程和浏览器之间开箱即用(。然后,我能够将数据从客户端发送到服务器,从服务器发送到客户端。我现在使用节点 0.6.12,使用节点 0.4.x 运行客户端有点痛苦。

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

据我了解,如果客户端首先从服务器请求了一些东西,则可以在服务器上调用方法。这是对的吗?

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

第一种方法是在服务器端定义一个寄存器函数,并从客户端传入回调。

服务器:

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