传递刚刚创建的参数

时间:2015-04-24 23:00:44

标签: javascript node.js function express anonymous-function

我正在创建一个NodeJS / Express监听器并且正在创建我的connectListener时正在创建的输入:

app.get('/server/:args', function(req, res) {
   res.sendFile(__dirname + '/index.html');
   // ... 
   var args = req.param("args");
   var client = net.connect({port : 50505}, connectListener(args, client));
});

然后我有connectListener功能:

function connectListener(args, client) {
    console.log("Connected to server.");
    console.log(args);
    client.write(args);
    // .... 
}

但是,我收到一个错误,即参数未定义:

TypeError: Cannot read property 'write' of undefined
    at connectListener (C:\Users\ES\workspace_luna\WptHash\server-src\index.js:39:8)
    at C:\Users\ES\workspace_luna\WptHash\server-src\index.js:33:43
    at Layer.handle [as handle_request] (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\layer.js:82:5)
    at next (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\route.js:100:13)
    at Route.dispatch (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\route.js:81:3)
    at Layer.handle [as handle_request] (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\layer.js:82:5)
    at C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\index.js:235:24
    at param (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\index.js:332:14)
    at param (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\index.js:348:14)
    at Function.proto.process_params (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\lib\router\index.js:392:3)
Error: Can't set headers after they are sent.
    at SendStream.headersAlreadySent (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\node_modules\send\index.js:313:13)
    at SendStream.send (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\node_modules\send\index.js:494:17)
    at onstat (C:\Users\ES\workspace_luna\WptHash\server-src\node_modules\express\node_modules\send\index.js:585:10)
    at FSReqWrap.oncomplete (fs.js:99:15)

那么,如何正确创建client变量,使其可以在下面的函数中使用?我正在制作这样的函数connectListener而不是内联的原因是我计划在更多端口上复制客户端以处理同时连接,因此我不想重新使用代码,也不想使用全局集合客户变量/数组(虽然我想我可以...)

1 个答案:

答案 0 :(得分:1)

看起来问题是你在调用connectListener,你应该把它设置为在connect事件上调用的函数:

var client = net.connect({port : 50505}, connectListener);

如果要写入具有特定args的特定客户端,可以通过在connectListener函数中定义响应来实现:

app.get('/server/:args', function (req, res) {
    var client, args;

    res.sendFile(__dirname + '/index.html');
    // ... 

   function connectListener () {
       console.log("Connected to server.");
       console.log(args);
       client.write(args);
       // .... 
   }

   args = req.param("args");
   client = net.connect({port : 50505}, connectListener);
});