【问题标题】:Identification of clients客户识别
【发布时间】:2015-07-16 03:35:26
【问题描述】:

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

TcpClient tcpClient = (TcpClient)client;

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

但我需要一个简单的整数,它可以分配给客户进行识别。每个连接的客户端该数字都会增加,因此我可以通过该数字识别哪个客户端正在执行操作。我该如何继续?

【问题讨论】:

  • 我已经编辑了我的问题。是的,一个整数计数器就可以了。

标签: c# connection tcpclient


【解决方案1】:

您可以创建您的自定义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
);

【讨论】:

    猜你喜欢
    • 2011-03-17
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 2018-08-13
    • 1970-01-01
    • 2023-02-20
    相关资源
    最近更新 更多