【发布时间】:2014-09-12 08:22:24
【问题描述】:
我正在尝试使用sailsjs 构建网络服务器。
为了执行它的请求,我的服务器需要连接到一个套接字来传递命令并等待响应。
对于每个命令,我等待特定的响应并且必须调用特定的回调。目前我只打开一个套接字并在每次请求时更改“onData”套接字。看起来效果不好,而且很丑。
另一种选择可能是为每个命令或请求打开和关闭一个套接字:我觉得它更糟糕。
有什么聪明的方法可以做我需要的吗?
已编辑:
这里是套接字(DriverConnection.js):
module.exports = {
connect: function(callback){
var net = require('net');
client = net.connect({port: 13}, function() { //'connect' listener
console.log('client connected');
callback();
});
},
command: function(command, callback){
client.write(command);
client.on('data', function(data) {
console.log("parsing data " + data.toString());
callback(JSON.parse(data.toString()));
});
}
};
这里是它的请求用法示例:
module.exports = {
list: function(req,res) {
DriverConnection.command('{}',function(data){
for(key in data) {
var mac = data[key];
Autoreez.findOne({name : mac},function (err,auto){
if(!auto) {
User.create({name : mac}, function(err,user){
res.send(user);
});
} else {
res.send(auto);
}
});
}
});
},
}
【问题讨论】:
标签: node.js sockets request client sails.js