对于我的家庭自动化系统,我想创建一个 NodeJS 服务,可以使用 net.connect() 连接到多个服务器。
我不知道如何管理该项目,目前我能够连接到一台服务器(发送和接收数据),该部分运行良好。
每个客户端都有一个 ID 和名称作为属性。
我认为我需要一系列网络客户端,但我找不到一个好的教程来实现它。
最佳答案
我设法让事情正常运转。
首先声明一些用于存储客户端的内容和连接方法:
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 :
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;
}
}
这实际上对我的项目来说效果很好,请随意讨论这个解决方案,谢谢您的帮助。
关于node.js - 如何在 Node.js 中管理多个网络客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40651242/