2012-12-09 40 views
1

以下是一个简单的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 

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

回答

2

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