Tcp接收数据包防止粘包

一般处理Tcp接收的不定长数据包时容易出现粘包现象,即tcp数据放入到缓冲区导致两个数据包的头尾相连导致不能区分,

最简单的处理,对数据包添加包头,记录这一数据包的大小。

先读包头,读出数据包大小

1 int head = sizeof(Head);
2 while(head)
3 {
4     ret = recv(socket,headbuf+sizeof(Head)-head,head,0);
5     if(ret<=0) throw -1;
6 }

根据包头中记录的包大小去读取Tcp缓冲的数据

int body = ((Head *)headbufer)->length;
while(body)
{
    ret = recv(socket,data+((Head *)headbufer)->length-body,body,0);
    if(ret<=0) throw -1;
}

 

posted @ 2021-03-28 18:41  SixHero  阅读(334)  评论(0)    收藏  举报