我正在制作一个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
像这样而不是内联,是因为我计划在更多端口上复制客户端以处理并发连接,所以我不想重复使用代码,也不希望使用全局的客户端变量/数组集(尽管我想我可以...) 最佳答案
看起来问题出在您正在调用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);
});