识别客户

时间:2015-05-06 06:38:13

标签: c# connection tcpclient

我有一台连接多个客户端的服务器。我想确定每个客户发生了什么。为此,我需要某种特定客户的某种身份识别。

TcpClient tcpClient = (TcpClient)client;

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

但我需要一个简单的整数,可以将其分配给客户端进行识别。并且每个连接的客户端的数量都会增加,因此我可以识别哪个客户端通过该号码进行操作。我该如何处理?

1 个答案:

答案 0 :(得分:2)

您可以创建自定义TcpClient类,其中Id字段的类型为int。每次建立新的客户端连接(因此TcpClient的新实例可用时),您必须创建MyClient的新实例并将其传递给新的TcpClient对象。静态计数器可确保MyTcpClient的每个新实例的Id增加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;   
   }    
}

您可以稍后使用它:

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