简体   繁体   中英

100% CPU Usage while running TCP server application

I have a tcp server application which accepts tcp clients in more number and receives continuous messages from all the connected clients.

public void KeepListening()
    {
        while (IsRunning)
        {
                try
                {
                        Thread.Sleep(20);
                        if (tcpListener.Pending())
                        {
                            //Get the socket obtained from the tcpListener
                            TcpClient _Client = tcpListener.AcceptTcpClient();
                            NetworkStream ns = _Client.GetStream();
                            Thread.Sleep(20);
                            if (Stop_Status == false)
                            {
                                if (_Client.Connected)
                                {
                                    int DataBytes = _Client.Available;
                                    byte[] data = new byte[DataBytes];
                                    if (ns.DataAvailable == true)
                                    {
                                        ns.Read(data, 0, DataBytes);
                                        string Key = ASCIIEncoding.ASCII.GetString(data);
                                        string[] KeyCodes = Key.Split(',');
                                        if (Key != "" && ((KeyCodes[0].StartsWith("i"))))
                                            ProcessClient(_Client, KeyCodes[0], Key);
                                    }
                                }
                            }
                            else
                            {
                                ns.Flush();
                            }
                        }
                }
                catch
                {

                }
        }
    }


    void ProcessClient(TcpClient _Client, string Key,string Msg)
    {
        try
        {
            if (hashTable_Users.Count > 0)
            {
                if (hashTable_Users.Contains(Key))
                {
                    hashTable_Users.Remove(Key);
                }
            }
            hashTable_Users.Add(Key, _Client);
            hashusers = hashTable_Users.Count;
            this.MessageFromClient(Key, serverPortNo.ToString(), Msg);

            //StreamWriter sw = new StreamWriter(_Client.GetStream());
            //sw.WriteLine("1");
            //sw.Flush();

            object[] objarr = new object[5];
            objarr[0] = _Client;
            objarr[1] = Key;
            Thread ReceiveFromClient = new Thread(new ParameterizedThreadStart(ReceiveFromClients));
            ReceiveFromClient.Start(objarr);
        }
        catch
        {

        }
    }
   public void ReceiveFromClients(object obj)
    {
            object[] objarr = (object[])obj;
            TcpClient _Client = (TcpClient)objarr[0];
            NetworkStream ns = _Client.GetStream();
            while (IsRunning)
            {
                if (Stop_Status == false)
                {
                    if (_Client.Connected)
                    {
                        if (ns.DataAvailable)
                        {
                            try
                            {
                                int numBytesRead = _Client.Available;
                                byte[] data = new byte[numBytesRead];
                                ns.Read(data, 0, numBytesRead);
                                string MsgReceived = ASCIIEncoding.ASCII.GetString(data);
                                string clientKey = objarr[1].ToString();
                                this.MessageFromClient(clientKey, serverPortNo.ToString(), MsgReceived);
                            }
                            catch
                            {

                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    ns.Flush();
                }
            }
    }

KeepListening() is used to accept the clients which send the request. ProcessClient() and ReceiveFromClients() are used to receive the messages from the clients.

This application is using 100% cpu.

Please suggest me what to do to decease the cpu utilization?

By looking into your code, ReceiveFromClients is consuming most of CPU, because of while (IsRunning) and in that you are reading if only data is available.

To solve this, dont check IsAvailabele, call ReadMethod which blocks the thread until ReadTimeOut occurs or some data has been read. Based on the number of bytes received, process your data.

Please suggest me what to do to decease the cpu utilization?

Well this looks like a bad start:

while (IsRunning)
{
    try
    {
        ...
    }
    catch
    {
    }
}

If you're repeatedly getting exceptions, you'll never know about it - and just keep looping. You've got another empty catch block, too... you really shouldn't catch everything and just keep going, without even logging.

Likewise here:

while (IsRunning)
{
    if (Stop_Status == false)
    {
        ...
    }
    else
    {
        ns.Flush();
    }
}

If IsRunning is true, and Stop_Status is false, that's just going to tight loop, calling Flush repeatedly...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM