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