网络编程之解决粘包问题的简单模型

int CServerSocket::processLoginPkt(const char *pkt, int index)
{
User user;
LoginPkt* loginPkt = (LoginPkt*)pkt;

strcpy(user.name, loginPkt->userName);
strcpy(user.password, loginPkt->password);


if (USER_FOUND == checkUser(&user))
{
if (strlen(userNames[index]) != 0)
sendReplyPkt(index, USER_IS_ONLINE);
else
{
sendReplyPkt(index, LOGIN_SUCCESS);
strcpy(userNames[index], loginPkt->userName);
broadcastFileList(index);
}
}
else
sendReplyPkt(index, LOGIN_FAIL);
return 0;
}

//上述函数是客户端处理登录包的。采用的TCP协议(流),会出现粘包问题的主要原因是客户端连续发送多次包(broadcastFileList()函数中有sendPkt函数,sendReplyPkt()函数中也有sendPkt函数),服务端接收的时候,会出现粘包情况。粘包出现的情况参考的链接是:http://hzp.iteye.com/blog/2212726

处理粘包的简单模型:

//建立一个临时缓冲区,接收包的时候,也接收包的长度,存储到临时缓冲区的时候对比包本身的长度,就可以知道该包是否接收完整。

int recvFile(const char* fileName)
{
FILE* fp = fopen(fileName, "w");
if(fp == NULL)
return -1;

int recvBytes;
while(1)
{
char buff[2048] = {0};//临时缓冲区
recvBytes = recv(sock, buff, 2048, 0);
if(recvBytes == 0)
{
fclose(fp);
return 0;
}
if(recvBytes < 0 )
{
fclose(fp);
return -2;
}

fwrite(buff, 1, recvBytes, fp);
}
}

posted @ 2017-06-09 17:01  林木子  阅读(282)  评论(0编辑  收藏  举报