【TCP】TCP 分包拆包代码
https://blog.csdn.net/xufengyongyou/article/details/45305947
void SockBox::AddBox(const char *data, const size_t size)
{
if (data)
{
m_data.SetDataSize(m_sizeBuf + size);
memcpy(m_data.GetData() + m_sizeBuf, data, size);
m_sizeBuf += size;
}
if (m_sizeBuf <= sizeof(m_size))
//包大小 未读全,待新包到达
return;
/*包大小获取*/
if (!m_size)
{
m_sizeBuf -= sizeof(m_size);
memcpy(&m_size, m_data.GetData(), sizeof(m_size));
memmove( m_data.GetData(),
m_data.GetData() + sizeof(m_size),
m_sizeBuf);
}
/*end 包大小获取*/
if (m_sizeBuf < m_size)
//半包 包未读全,待新包到达
return;
/*粘包处理*/
if (m_host->GetCallBack())
m_host->GetCallBack()(m_data.GetData(), m_size, this);
m_sizeBuf -= m_size;
if (m_sizeBuf)
{
memmove(m_data.GetData(),
m_data.GetData() + m_size,
m_sizeBuf);
}
m_size = 0;
//递归处理粘包
AddBox(nullptr, 0);
/*end 粘包处理*/
}