无法将TCP响应数据写入变量

时间:2014-07-15 10:45:35

标签: node.js sockets tcp

导出模型的问题是[对象内部的可见性和对函数的异步调用]。

 exports.send = function(socket, req, callback) {

  req.external_response = {};                      //  initialize empty object

  client.connect(socket.Port, socket.IPAddress, function() {
    client.write(req.query);
  });

  client.on('data', function(data, req) {                                   
    req.external_response = data.toString('utf8');// assign response to it
                                        // console.log(req.external_response); gives out response
  });

  client.on('close', function() {
    client.destroy();
    callback();
  });
};

发送完成并回调执行后我仍然有

  

req.external_response = {}

如果我这样做

var tmp = "";
client.on('data', function(data) {
    tmp = data.toString('utf8');// assign response to it
                                // console.log(tmp); gives out 
  });
req.external_response = tmp;    // tmp 'undefined'

我尝试了各种方法将数据写入变量但到目前为止没有成功,也许有些东西我没有注意到/错过。任何建议如何编写TCP响应到所需的变量?

2 个答案:

答案 0 :(得分:0)

第一个代码段可能因为变量冲突而无效:

exports.send = function(socket, req, callback) {

  req.external_response = {};

  client.on('data', function(data, req2) {   // <----- req2 !!!
    req.external_response = ...
  });

  client.on('close', function() {
    console.log(req.external_response);
    client.destroy();
    callback();
  });

};

第二个片段:

var tmp = "";
client.on('data', function(data) {
    tmp = data.toString('utf8');// assign response to it
                                // console.log(tmp); gives out 
  });
req.external_response = tmp;

将无效,因为您会在回调为其分配数据之前将tmp分配给req.external_response

答案 1 :(得分:0)

这是我试图达到我想要的东西:(没有结果所有'')

1

var assignData = function(source, destination){
destination = source.toString('utf8');
callback();
};

 client.on('data', function(data) {
assignData(data,req.external_response);
});

2

client.on('data', function(data) {
req.external_response = data.toString('utf8');
callback();

});

调用.send(socket,req,callback)

var req = {query:'0000000082&ServiceID=2355&QueryCode=8080'};
sender.send(req, {}, done);