断开连接后访问套接字对象

以下是一个简单的Node.js tcp服务器。

var net = require('net'); var conn = []; var server = net.createServer(function(client) {//'connection' listener var i = conn.push(client) - 1; //console.log('[conn',i,']', client.remoteAddress, ':', client.remotePort); console.log('[disc]', conn[i].remoteAddress, ':', conn[i].remotePort); client.on('end', function() { console.log('[disc]', conn[i].remoteAddress, ':', conn[i].remotePort); }); client.on('data', function(msg) { console.log('[data]', msg.toString()); }) client.write('hello\r\n'); //client.pipe(client); }); server.listen(8080); 

当客户端连接,发送或断开时,它将打印有关客户端的信息。 但是,只有客户端断开连接时,才会打印undefined的套接字信息。 例:

 [conn] 127.0.0.1 : 52711 [data] 127.0.0.1 : 52711 world! [disc] undefined : undefined 

为什么会发生? 这是因为当它closures套接字被破坏? 我需要知道有关closures套接字的信息。

断开的套接字没有远程端点,因此没有远程地址或远程端口。 套接字没有被破坏,它只是不再连接。 如果您需要在套接字断开后知道远程地址和端口,则需要自行跟踪。