SMVS series (3)



  • There's a SMVS server hanging on the 25th port of the local car. When he catches the connection, he handles the client in a separate flow.

    But that's what happens when it's just launched, it's 0.0% CPU, after it's caught the first connection 25%CPU, then 50 and so to 100, and it's.

    I tried to put Thread.Sleep(100) but it didn't work.

    The most interesting thing is that after the connection to the client is ruptured, the load of the CPU does not fall.

    Question: How do you make the service not smash the CPU but release it? I feel like I need some = null, but it didn't work.

    Code itself:

    protected override void OnStart(string[] args) {
    
    SmtpHelper s = new SmtpHelper(this);
    
    Thread listen = new Thread(new ThreadStart(s.Listen));
    listen.Start();
    

    }

    Then:

    public void Listen() {
    int iter = 0;

    try {
        l.Write("***************START*******************");
        l.Write("SMTP server started " + DateTime.Now.ToString());
    
        SMTP_Listener = new TcpListener(IPAddress.Any, port);
        SMTP_Listener.Start();
    
        while (true) {
            /*Создадим сначала номер потока и файл логов для него*/
            Socket clientSocket;
            clientSocket = SMTP_Listener.AcceptSocket();
    
            m_ConnectedIp = ParseIP_from_EndPoint(clientSocket.RemoteEndPoint.ToString());
            m_ConnectedHostName = GetHostName(m_ConnectedIp);
            _email.ip = m_ConnectedIp;
            _email.port = 25;
    
            //номер сессии(клиента)
            _sessionId = clientSocket.GetHashCode().ToString();
            _email.sessionId = Convert.ToInt32(_sessionId);
    
            l.Write("New session: " + _sessionId);
            l.Write("Создан поток для обработки клиента " + _sessionId);
    
            //запускаем обработку клиента
            var processor = new ClientProcessor(clientSocket, m_ConnectedIp, m_ConnectedHostName, _email, MaxMessageSize, CommandIdleTimeOut);
            processor._sessionId = _sessionId;
            UserSessionController.AddSession(Convert.ToInt32(_sessionId));
    
            Thread newClient = new Thread(processor.StartProcessing);
            newClient.Name = _sessionId;
            newClient.IsBackground = true; // ???
            newClient.Start();
            l.Write("*********************************************************");
        }
    } catch (Exception ex) {
        l.Write("SMTP Listen Error: " + ex.ToString());
        throw;
    }
    

    }

    StartProcessing:

    /// <summary>
    /// Основной цикл работы сервера
    /// </summary>
    public void StartProcessing() {
    try {
    string namethread = _sessionId;

        l.Write(String.Format("Клиент {0}: _connectedIp = {1}, _connectedHostName = {2}", _sessionId, _connectedIp,
        _connectedHostName), namethread);
    
        if (_clientSocket.Connected) {
            l.Write("&gt;&gt;&gt;Socket connected", namethread);
        } else {
            l.Write("&lt;&lt;&lt;Socket NOT connected", namethread);
        }
    
        SendData("220 " + System.Net.Dns.GetHostName() + " Service ready\r\n");
        l.Write("'220 " + System.Net.Dns.GetHostName() + " Service ready' были отправлены клиенту", namethread);
    
        //РАБОТА С ВХОДНЫМИ ДАННЫМИ
        while (true) {
            //если есть данные, то считаем их
            if (_clientSocket.Available &gt; 0) {
                //чтение команды клиента
                string lastCmd = ReadLine();
    
                if (lastCmd.Trim() == String.Empty) {
                    l.Write("Empty commmand (lastCmd)]", namethread);
                } else {
                    l.Write("lastCmd: " + lastCmd, namethread);
                }
    
                //парсим команду
                if (lastCmd.Trim() != String.Empty) ProceedCommand(lastCmd, namethread);
            } else {
                //dump:  l.Write("[Socket isn't available now]");
            }
        }
    } catch (Exception ex) {
        l.Write("SMTP StartProcessing Error: " + ex.ToString());
        throw;
    }
    

    }



  • while (true)
    {
        //если есть данные, то считаем их
        if (_clientSocket.Available > 0) чаще всего false
        {
             ReadLine();
        }
    }
    

    It's, in fact, an endless cycle that loads the processor even if the data don't come. Inside ReadLine You're probably Socket.Receivewhich already blocks compliance before the data arrives. So just take it away.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2