Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# TcpListener如何连接客户端?_C#_Tcplistener - Fatal编程技术网

C# TcpListener如何连接客户端?

C# TcpListener如何连接客户端?,c#,tcplistener,C#,Tcplistener,我有一个连接到多个客户端的TcpListener。我可以获得所有已连接客户端的列表吗?我认为最好的方法是在打开连接时将客户端添加到列表中: public TcpClient connectedClients = new list<TcpClient>(); public void ConnectClient(int ip, int port) { tcp.Connect(ip, port); connectedClients.Add(tcp); } 因为当您关闭T

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

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

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

public void ConnectClient(int ip, int port)
{
    tcp.Connect(ip, port);
    connectedClients.Add(tcp);
}
因为当您关闭TCP客户端时,所有连接都已断开,所以您最好清除该列表


希望这有帮助。

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

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);
}
TcpListener服务器=新的TcpListener(端口);
服务器=新的TcpListener(localAddr,端口);
//开始侦听客户端请求。
server.Start();
List ListConnectedClient=新列表();
while(true)
{
TcpClient client=server.AcceptTcpClient();
ListConnectedClient.Add(客户端);
}

@BewareSalah您可以在接受时手动将
TcpClient
s保存在列表中。我认为这是唯一的方法;-)是的,我查看了文档,但找不到提供已接受连接列表的方法或属性。如果其中一个客户端断开连接怎么办?如何将其从列表中删除?@BewarSalah您必须为每个新的客户端连接打开一个新线程,并打开一个网络流以从客户端读取。如果您收到类似SocketException的异常,或者关闭了客户端连接,则需要将其从列表中删除。请注意,这里需要一个线程安全列表。@BewarSalah:您可以将这些用于引用:套接字连接:线程安全列表:如果某个客户端断开连接怎么办?如何将其从列表中删除?
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);
}