Identification of clients

2019-06-08 20:06发布

问题:

I have a server to which multiple clients are connected. I want to identify what is happening with each client. For this, I need some kind of identification for a particular client.

TcpClient tcpClient = (TcpClient)client;

 logger.DebugFormat("Connection obtained with a client {0} {1} {2} ", client.Connected, client.Client.LocalEndPoint,client.Client.RemoteEndPoint);

But I need a simple integer number which can be assigned to a client for its identification. And that number increments for every client connected and thus I can identify which client is acting through that number. How can I proceed with this?

回答1:

You can create your custom TcpClient class which will have Id field of type int. Each time a new client connection is made (and so a new instance of TcpClient is available) you have to create a new instance of MyClient and pass it this new TcpClient object. Static counter makes sure that each new instance of MyTcpClient has Id increased by 1.

public class MyTcpClient
{
   private static int Counter = 0;

   public int Id
   {
      get;
      private set;
   } 

   public TcpClient TcpClient
   {
      get;
      private set;
   }

   public MyTcpClient(TcpClient tcpClient)
   {
      if (tcpClient == null)
      {
         throw new ArgumentNullException("tcpClient") 
      }

      this.TcpClient = tcpClient;
      this.Id = ++MyTcpClient.Counter;   
   }    
}

You can use it later as:

logger.DebugFormat(
   "Connection obtained with a client {0} {1} {2} {3}", 
   myClient.Id, 
   myClient.TcpClient.Connected,   
   myClient.TcpClient.Client.LocalEndPoint,
   myClient.TcpClient.Client.RemoteEndPoint
);