Socket.Receive cpu full load in C# tcp server
DS DS
1
Reputation point
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!