Identification of clients

后端 未结 1 1760
梦谈多话
梦谈多话 2020-12-20 07:14

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

相关标签:
1条回答
  • 2020-12-20 07:49

    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
    );
    
    0 讨论(0)
提交回复
热议问题