Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to keep track of connected clients on TCP?

I wrote a small demo client/server TCP sockets project based off a number of tutorials I found through stack.

Currently the the project is blocking, and I dedicate a thread to each client. This is far from ideal, but I wanted to get familiar with basic sockets before working with Async.

None of the the tutorials I have read have really explained how to keep track of your current connections for reporting, etc., so I just explored this on my own:

private Dictionary<IPAddress, DateTime> connectedClients = new Dictionary<IPAddress, DateTime>();

So my question is: What is the best way to keep track of my connected clients?

Follow-up Question: How do you deal with testing? If all of the connections are coming from the same machine (same IP, same MAC), how do you make sure entries are unique? A reference to a client object? A GUID? Both?

Thanks.

like image 756
Ray Avatar asked Apr 15 '26 06:04

Ray


2 Answers

I would just keep a list of Sockets returned by TcpListner.Accept(). When a client disconnected remove the socket from the list. Information about the remote endpoint (for reporting) can be retrieved from the RemoteEndPoint property.

like image 136
Yaur Avatar answered Apr 16 '26 20:04

Yaur


The combination of ip and port for both client and server is unique for TCP connections and for UDP connections the combination of client and server ports are unique.

TCP connection: (server ip address, server port,client ip address, client port)

UDP connection: (server port,client port)

are unique.

like image 42
mehdi.loa Avatar answered Apr 16 '26 20:04

mehdi.loa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!