【问题标题】:How to manage multiple net clients in Node.js如何在 Node.js 中管理多个网络客户端
【发布时间】:2017-03-31 18:42:22
【问题描述】:

对于我的家庭自动化系统,我想创建一个 NodeJS 服务,它可以使用 net.connect() 连接到多个服务器。

我不知道如何管理该项目,目前我能够连接到一台服务器(发送和接收数据),该部分运行良好。

每个客户端都有一个 id 和 name 作为属性。

我想我需要一组网络客户端,但我找不到一个好的教程来让它工作。

【问题讨论】:

    标签: node.js server client


    【解决方案1】:

    我设法让事情顺利进行。

    首先声明一些东西来存储客户端和连接方法:

    var nodes = [];
    
    var node;
    node = new events.EventEmitter(); // Maybe we can use something else ?
    
    node.connect = function (id, name, host, port) {
        var node = net.connect({host:host, port:port});
        node.id = id;
        node.name = name;
        node.
        on('connect', function () {
            // we are connected
            node.is_connected = true;
        }).
        on('close', function () {
            // we are closed
            node.is_connected = false;
            node.destroy();
        }).
        on('error', function (err) {
            // there is an error
        }).
        on('data', function (data) {
            // we have data
        });
        // add thos new node to storage
        nodes.push(node);
    }
    

    添加一个新节点:

    node.connect(id, name, host, port);
    

    要删除一个,也许我们可以以更好的方式做到这一点,也许是通过 Id (?) 获取:

    for (var i = 0, len = nodes.length; i < len; i++) {
        if (nodes[i].id == id) {
            nodes[i].destroy();
            nodes.splice(i, 1);
            break;
        }
    }
    

    这实际上对我的项目很有效,请随时讨论此解决方案,感谢您的帮助。

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多