C# 具有动态ip地址的服务器客户端
我有一个内置于C#中的服务器应用程序,它监听tcp端口并从客户端接收一些数据包。问题是有一些客户端具有动态ip地址,所以目前我有一个客户端打开了更多连接。我需要一种方法来确定客户端何时更改其ip并关闭旧连接C# 具有动态ip地址的服务器客户端,c#,sockets,tcplistener,dynamic-ip,C#,Sockets,Tcplistener,Dynamic Ip,我有一个内置于C#中的服务器应用程序,它监听tcp端口并从客户端接收一些数据包。问题是有一些客户端具有动态ip地址,所以目前我有一个客户端打开了更多连接。我需要一种方法来确定客户端何时更改其ip并关闭旧连接 List<Socket> ClientsToRemove = new List<Socket>(); ---this foreach this to avoid connections with the same ip address---
List<Socket> ClientsToRemove = new List<Socket>();
---this foreach this to avoid connections with the same ip address---
foreach(Socket client1 in AllConnections)
{
int count = 0;
foreach(Socket client2 in AllConnections)
{
if(((IPEndPoint)client1.RemoteEndPoint).Address.ToString() == ((IPEndPoint)client2.RemoteEndPoint).Address.ToString())
{
count++;
}
}
if(count>1)
{
AllConnections.Remove(client1);
UpdateActiveConnectionsBox(AllConnections.Count.ToString());
}
}
---verify active connections---
foreach (Socket client in AllConnections)
{
if (!client.IsConnected())
{
ClientsToRemove.Add(client);
}
else
{
UpdateLogBox("Active client IP:" + ((IPEndPoint)client.RemoteEndPoint).Address.ToString());
}
}
UpdateLogBox("ACtive connection numer: " + AllConnections.Count.ToString());
foreach (Socket client in ClientsToRemove)
if (AllConnections.Contains(client))
AllConnections.Remove(client);
ClientsToRemove.Clear();
ClientsToRemove = null;
UpdateActiveConnectionsBox(AllConnections.Count.ToString());
Thread.Sleep(1500);
只需“验证”步骤就足以清理旧连接。(顺便说一句,没有必要通过清除集合并将变量设置为
null
来“帮助”GC。它知道在foreach(ClientsToRemove中的套接字客户端)
执行之后(假设您删除了我说过的代码)没有其他东西从ClientsToRemove
变量读取,因此它不是有效的根,无法保持它引用的任何对象处于活动状态),而且我仍然有34个客户端(我肯定知道)和41个打开了不同ip的连接:)您的连接保持打开状态多长时间?动态客户端通常不会频繁更改其IP地址。根据我在ADSL上的经验,每隔几周就有一次,但在有线电视上几乎从来没有。那么你确定这是因为客户端更改了他们的IP地址吗?(如果客户机确实更改了其IP地址,那么我会认为这会中断连接。)使用动态IP地址,IP地址可以重新分配给其他PC机。因此,无法仅使用验证同一客户机的IP地址(没有PC名称)。您可以使用以下命令获取主机名(取决于dns的设置方式):IPHostEntry hostEntry=dns.GetHostEntry(iPAddress);machineName=hostEntry.HostName;昨天我添加了“foreach避免使用相同ip地址的连接”。在此之前,在服务器运行的两天内,我打开了3000多个连接,这些连接都具有相同的ip…所以我也不明白为什么连接没有关闭。我敢说,它们永远都是开着的
ServerMainSocket.Listen(10);
Socket TempSock = ServerMainSocket.Accept();
Task.Factory.StartNew(() => { ClientFunction(TempSock); });
UpdateLogBox("New client connected from IP:" + ((IPEndPoint)TempSock.RemoteEndPoint).Address.ToString());
if(AllConnections.Contains(TempSock) != true)
{
AllConnections.Add(TempSock);
}
else
{
AllConnections.Remove(TempSock);
AllConnections.Add(TempSock);
UpdateActiveConnectionsBox(AllConnections.Count.ToString());
}