我正在构建一个简单的echo服务器,目的是学习使用node.js构建tcp服务的基础知识,并找出可用的信息。
当我创建服务器时,如下所示,我可以访问有关incomingSocket的信息,例如远程地址。为什么我无法访问关闭套接字的信息?以下是我的代码;我的评论表明我收到的输出。
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
我很感激任何回应!谢谢!
答案 0 :(得分:4)
嗯不,因为当它进入套接字关闭事件的事件处理程序时,套接字对象不再存在。如果您需要在套接字关闭时显示客户端的远程地址,只需在客户端最初连接时存储远程地址。
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.');
});
...