При программировании сокетов память файла exe постепенно увеличивается, а сокет остается открытым - PullRequest
0 голосов
/ 12 июня 2018

При получении жала от нескольких клиентов время от времени некоторые сокеты остаются открытыми, поэтому размер файла увеличивается постепенно, поэтому размер исполняемого файла становится 2 ГБ по сравнению с 35 КБ, так как я могу уменьшить открытый сокет

private void Server_Load(object sender, EventArgs e)
{
  try
   {
        this.tcpListener = new TcpListener(IPAddress.Any, port);
        this.listenThread = new Thread(new ThreadStart(ListenForClients));
        this.listenThread.Start();
   }
  catch (Exception ex)
  { }
  finally
  {
    if (this.tcpListener != null)
    {
        this.tcpListener.Stop();
    }
  }
} 

МангиКлиентский запрос к серверу непрерывно из метода загрузки

private void ListenForClients()
{
 TcpClient client = null;
 try
 {
    this.tcpListener.Start();
    while (true)
    {
         client = this.tcpListener.AcceptTcpClient();
        ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClientComm), 
     client);
    }
 }
 catch (Exception ex)
 {
    LogHelperISPL.Logger.Info("ListenForClients: " + ex.Message);
    this.tcpListener.Stop();
 }
 finally
 {
    if(this.tcpListener != null)
    {
        this.tcpListener.Stop();
    }
    if (client != null)
    {
        client.Close();
    }
 }
}

Возьмите данные от клиента и вставьте в таблицу и управляйте проходом tcpclient и сетевым потоком при закрытом соединении

private void HandleClientComm(object client)
{
 TcpClient tcpClient = null;
 NetworkStream clientStream = null;
 try
 {
    tcpClient = (TcpClient)client;
    clientStream = tcpClient.GetStream();
    string InsertedRecord = string.Empty;
    byte[] messageBytes = new byte[4096];
    int bytesRead;
    bool end = false;
    while (!end)
    {
        bytesRead = 0;
        try
        {
            if (clientStream != null)
            {
                bytesRead = clientStream.Read(messageBytes, 0, 
            messageBytes.Length);
            }                        
        }
        catch (SocketException ex)
        {
            if (clientStream != null)
            {
                clientStream.Flush();
                clientStream.Close();
            }
            if (tcpClient != null)
            {
                tcpClient.Close();
            }
            break;
        }
        catch (Exception ex)
        {
            if (clientStream != null)
            {
                clientStream.Flush();
                clientStream.Close();
            }
            if (tcpClient != null)
            {
                tcpClient.Close();
            }
            break;
        }
        if (bytesRead <= 0)
        {
            break;
        }
        ASCIIEncoding encoder = new ASCIIEncoding();
        string Datareceived = encoder.GetString(messageBytes, 0, bytesRead);
        if (!string.IsNullOrEmpty(Datareceived))
        {
            string[] Multistrings = Datareceived.Split('!');
            for (int i = 0; i < Multistrings.Length; i++)
            {
                if (!string.IsNullOrEmpty(Multistrings[i]))
                {
                    if (Multistrings[i].Length >= 90)
                    {
                        InsertedRecord = InsertRawData(Multistrings[i]);
                    }
                    else
                    {
                        InsertedRecord = 
       InsertRawDataGarbage(Multistrings[i]);
                    }
                }
            }
        }
    }
 }
 catch (Exception ex)
 {
    LogHelperISPL.Logger.Info("While loop: " + ex.Message);
 }
 finally
 {
    if (clientStream != null)
    {
        clientStream.Flush();
        clientStream.Close();
    }
    if (tcpClient != null)
    {
        tcpClient.Close();
    }
 }
}
...