分包黏包问题解决方案

大耗子 2020年03月13日 155次浏览

文章链接:https://codemouse.online/archives/2020-03-13202900

在接收数据的时候,有可能没有一次接收结束,产生分包黏包,所以要做重复接收.

int recvPacket(int epollfd, char *buf)
{
	char packet[MAXBUFLEN] = { 0 };
	char * packetPtr = packet;
			
	int nBytesNeed = MAXBUFLEN;
	int nBytesRecv = 0;
    int nBytesSum =0;

    
	while( nBytesNeed > 0 )
	{
		nBytesRecv  = read(epollfd, packetPtr, nBytesNeed);
		
		if(nBytesRecv == -1 || nBytesRecv == 0) break;
		
		nBytesNeed -= nBytesRecv;
		packetPtr  += nBytesRecv;
        nBytesSum  += nBytesRecv;
	}

    if(nBytesSum == 0 || nBytesSum==-1 )
        return 0;
    
	strcpy(buf, packet);
	return nBytesSum;
}