Nodejs TCP套接字在结束时不包含remoteAddress信息

我正在构build一个简单的echo服务器,目的是学习有关使用node.js构buildtcp服务的基础知识,并确定可用的信息。

当我创build服务器时,如下所示,我可以访问有关incomingSocket的信息,如远程地址。 为什么我不能访问closuressocket的信息? 以下是我的代码; 我的评论表明我收到的输出。

var net = require ( 'net' ); var server = net.createServer ( function ( incomingSocket ) { //'connection' listener console.log ( 'Connection from ' + incomingSocket.remoteAddress + ':' + incomingSocket.remotePort + " established." ); incomingSocket.on ( 'data' , function ( data ) { // The incomingSocket.remoteAddress is defined here console.log ( incomingSocket.remoteAddress + ':' + incomingSocket.remotePort + ' -> ' + data.toString () ); } ); incomingSocket.on ( 'close' , function () { // The incomingSocket.remoteAddress is undefined here console.log ( 'connection from ' + incomingSocket.remoteAddress + ' closed.' ); } ); incomingSocket.pipe ( incomingSocket ); } ); // listening to a port happens here 

我将不胜感激任何回应! 谢谢!

Solutions Collecting From Web of "Nodejs TCP套接字在结束时不包含remoteAddress信息"

那么不,因为当它进入套接字closures事件的事件处理程序时,套接字对象不再存在。 如果您需要在套接字closures时显示客户端的远程地址,只需在客户端初始连接时存储远程地址即可。

 var clients = new Array(); net.createServer(function(socket) { var remoteAddress = socket.remoteAddress; var remotePort = socket.remotePort; // Add to array of clients clients.push(remoteAddress + ':' + remotePort); console.log('Connection from ' + remoteAddress + ':' + remotePort + " established."); socket.on('data', function(data) { console.log(remoteAddress + ':' + remotePort + ' -> ' + data.toString()); }); socket.on('close', function() { // Remove from array of clients clients.splice(clients.indexOf(remoteAddress + ':' + remotePort), 1); console.log('Connection from ' + remoteAddress + ':' + remotePort + ' closed.'); }); ...