TcpListener How to get Connected Clients?

Bewar Salah picture Bewar Salah · Jan 30, 2016 · Viewed 9.5k times · Source

I have a TcpListener that is connected to multiple clients. Can I get a list of all connected clients?

Answer

asdfasdfadsf picture asdfasdfadsf · Jan 30, 2016

I think the best way would be to just add the client to a list when opening the connection:

public TcpClient connectedClients = new list<TcpClient>();

public void ConnectClient(int ip, int port)
{
    tcp.Connect(ip, port);
    connectedClients.Add(tcp);
}

If you disconnect one of the clients:

public void DisconnectClient(int ip, int port)
{
    tcp.Close();
    connectedClients.RemoveRange(0, connectedClients.Length)
}

Since when you close a TcpClient all connections are disconnected you might as well clear the list.

Hope this helps.