Socket.Receive cpu full load in C# tcp server

DS DS 1 Reputation point
2021-03-29T17:14:55.177+00:00

Hello, the below code causes cpu full load for unknown reason.

    public void RecvThread()
    {
        try
        {
            const int PACKET_SIZE_MAX = 16384;

            while (true)
            {
                if (!m_hClient.Connected || !m_hClient.Client.Connected)
                    break;

                byte[] buf = new byte[PACKET_SIZE_MAX];
                int len;

                // 1. Keep the data by MSG_PEEK
                if ((len = m_hClient.Client.Receive(buf, PACKET_SIZE_MAX, SocketFlags.Peek)) <= 0)
                    break;

                // 2. Find if in these data, there is any '\r'. If not, then continue the loop again
                int iPosOfSeperator = -1;
                for (int i = 0; i < len; i++)
                {
                    if (buf[i] == (byte)'\r')
                    {
                        iPosOfSeperator = i;
                        break;
                    }
                }

                if (iPosOfSeperator == -1)
                    continue;

                // 3. read the data again within a length before \r  without MSG_PEEK
                if ((len = m_hClient.Client.Receive(buf, 0, iPosOfSeperator + 1, SocketFlags.None)) <= 0)
                    break;

                // remove the '\r'
                len -= 1;

                HandlePacket(buf, 0, len);
            }
        }
        catch (Exception)
        {
        }
        Disconnect();
    }

This code will receive packets separated with '\r' char to make sure each packet are received completely

The profiler said the m_hClient.Client.Receive is using full cpu. Please help!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,205 questions
{count} votes