6

我有一个简单的 TCP 服务器,如下所示:

var net = require('net');
var PORT = 6346;

var server = net.createServer(function(socket) {

    socket.on('connect', function() {
        console.log('Client connected: ' + socket.remoteAddress);
        socket.write('Welcome to the server!\r\n');
    });

    socket.on('end', function() {
        console.log('Client disconnected: ' + socket.remoteAddress);
    });

    socket.on('error', function() {
        console.log('Client error: ' + socket.remoteAddress);
    });

    socket.on('timeout', function() {
        console.log('Client timed out:' + socket.remoteAddress);
    });


}).listen(PORT);

当我连接到服务器时,我看到了预期Client connected: 127.0.0.1,但是当我断开连接时,我看到了Client disconnected: undefined. 为什么 socket.remoteAddress 未定义,如何在断开连接时记录客户端的 IP?

4

3 回答 3

10

问题是套接字断开后,某些属性(例如remoteAddress)不再可用!

您可以通过使用自己的对象包装套接字来解决此问题,或者在连接时在其他地方跟踪该远程地址。(为关闭而努力。)

于 2012-09-16T05:30:33.107 回答
2

一旦https://github.com/joyent/node/commit/8c38b07252d86f4eef91344f8df4f0c3e38bca35在 Node.js 的稳定版本中,即使断开连接,remoteAddress 属性也会存在。io.js 将在下一个版本中包含它:https ://github.com/iojs/io.js/issues/1157

于 2015-03-17T03:20:51.197 回答
0

在尝试从某些服务器调试 504 错误时,我发现更改此代码

request(url, function (error, response, body) {
    if (error) {
        callback(error);
    } else {
        if (response.statusCode == 200) {
            callback(null, body);
        } else {
            // response.connection.remoteAddress is undefined here
            callback(new Error("Non status 200: " + response.statusCode + " received from " + response.connection.remoteAddress + " when requesting " + url));
        }
    }
});

到这个代码

request(url, function (error, response, body) {
    if (error) {
        callback(error);
    } else {
        if (response.statusCode == 200) {
            callback(null, body);
        } else {
            // response.connection.remoteAddress is now magically set somehow
            callback(new Error("Non status 200: " + response.statusCode + " received from " + response.connection.remoteAddress + " when requesting " + url));
        }
    }
}).on('response', function(response) {
    // This next line is very important.  It seems to make the remoteAddress variable stay in the socket so we can read it.
    let remoteAddress = response.connection.remoteAddress;
});

似乎工作。我不知道为什么在响应处理程序中访问 remoteAddress 变量会使其停留在阅读状态。

于 2019-06-12T16:07:53.800 回答