1

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

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

4

1 回答 1

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

   ...
于 2012-06-14T18:25:34.977 回答