4

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

Bewar Salah
  • 567
  • 1
  • 5
  • 15

2 Answers2

3

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.

asdfasdfadsf
  • 381
  • 3
  • 14
3

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);
}
frostedcoder
  • 153
  • 7
  • I think this is the only way ;-) – code4life Jan 30 '16 at 19:26
  • Yep, I checked the documentation and I could not find a method or property that gives a list of accepted connections. – frostedcoder Jan 30 '16 at 19:28
  • 2
    What if one the clients is disconnected? How to remove it from the list? – Bewar Salah Jan 30 '16 at 20:01
  • @BewarSalah You'd have to open a new thread with each new client connection and open a network stream to read from the client. If you get an exception like SocketException or if you close the client connection, you need to remove it from the list. Note that you'd need a thread safe list here. – frostedcoder Jan 30 '16 at 20:12
  • @BewarSalah: You can use these for references: Socket Connection: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=vs.110).aspx Thread safe list: http://stackoverflow.com/questions/9995266/how-to-create-a-thread-safe-generic-list – frostedcoder Jan 30 '16 at 20:18