Identification of clients

£可爱£侵袭症+ 提交于 2019-12-18 07:19:58

问题


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
);


来源:https://stackoverflow.com/questions/30069278/identification-of-clients

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!