【问题标题】:Scope of variables to callback functions回调函数的变量范围
【发布时间】:2012-08-08 23:24:40
【问题描述】:

我正在使用 TLS 模块在 node.js 中创建一个简单的服务器。到目前为止一切顺利,客户端能够连接、发送数据和断开与服务器的连接。但是,我想在与服务器断开连接时打印客户端的 IP 地址。就目前而言,我可以从事件回调函数之外打印客户端的 IP 地址,但我不能在回调函数中这样做(检查on('end))。

var tls = require('tls');
var fs = require('fs');

var server = tls.createServer({
    key: fs.readFileSync('server-key.pem'),
    cert: fs.readFileSync('server-cert.pem'),
}, function(cleartextStream) {
    cleartextStream.setEncoding('utf8');

    /*
     * Error receiving data.
     */
    cleartextStream.on('error', function (exception) {

    });

    /*
     * Signal that it is safe to write again.
     */
    cleartextStream.on('drain', function () {

    });

    /*
     * New data received.
     */
    cleartextStream.on('data', function (data) {
        console.log('New data: '+data);
    });

    /*
     * Remote client disconnected.
     */
    console.log(cleartextStream.remoteAddress); // This prints the IP address correctly.

    cleartextStream.on('end', function () {
        console.log(cleartextStream.remoteAddress); // This prints undefined.
    });

    /*
     * Server is shutting down.
     */
    cleartextStream.on('close', function () {

    });
});

server.listen(8000, function() {
  console.log('Server listening.');
});

【问题讨论】:

    标签: node.js scope


    【解决方案1】:

    看起来cleartextStreamremoteAddress 属性在'end' 事件触发之前已被删除。所以捕获远程地址,以便它在您的'end' 事件回调中仍然可用:

    var remoteAddress = cleartextStream.remoteAddress;
    cleartextStream.on('end', function () {
        console.log(remoteAddress);
    });
    

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      • 2013-08-07
      • 2012-10-20
      • 2014-10-06
      • 2010-11-01
      • 1970-01-01
      相关资源
      最近更新 更多