gpt4 book ai didi

sockets - Nodejs TCP套接字,结束时不包含remoteAddress信息

转载 作者:可可西里 更新时间:2023-11-01 02:45:38 25 4
gpt4 key购买 nike

我正在构建一个简单的回显服务器,目的是学习有关使用 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

如有任何回复,我将不胜感激!谢谢!

最佳答案

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

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.');
});

...

关于sockets - Nodejs TCP套接字,结束时不包含remoteAddress信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10391797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com