TcpListener 如何获取已连接的客户端?

TcpListener How to get Connected Clients?

我有一个连接到多个客户端的 TcpListener。我可以获得所有已连接客户端的列表吗?

我认为最好的方法是在打开连接时将客户端添加到列表中:

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

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

如果您断开其中一个客户端:

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

因为当您关闭 TcpClient 时所有连接都断开连接,您最好清除列表。

希望对您有所帮助。

您可以在服务器上接受连接时将客户端放入列表中。

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