TcpListener How to get Connected Clients?

10,446

Solution 1

You can put the client in a list when you accept a connection on the server.

TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);

// Start listening for client requests.
server.Start();

List<TcpClient> listConnectedClients =  new List<TcpClient>();
while(true)
{
    TcpClient client = server.AcceptTcpClient();
    listConnectedClients.Add(client);
}

Solution 2

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.

Share:
10,446
Bewar Salah
Author by

Bewar Salah

I am coding when I am free. I am eager to find more about Multi-Threading, Linq and Reflection. I really want to give what I take.

Updated on August 21, 2022

Comments

  • Bewar Salah
    Bewar Salah over 1 year

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