具有动态IP地址的服务器客户端

时间:2018-09-06 10:03:35

标签: 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---                 
                   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());
}

0 个答案:

没有答案