我有一个用 C# 构建的服务器应用程序,它监听一个 tcp 端口并从客户端接收一些数据包。问题是有动态 IP 地址的客户端,所以此刻我有一个客户端打开了更多连接。我需要一种方法来确定客户端何时更改其 ip 并关闭旧连接。
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);
这就是我接受新连接的地方:
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());
}