这是网上流传很广泛的TCP粘包处理代码:
fd_set fdRead;
timeval TimeOut;
PACKHEADER *pHead = (PACKHEADER *)pBuffer;
int ret, nLeft = 0, idx = 0;
TimeOut.tv_sec = 0;
TimeOut.tv_usec = TIMEOUT;
FD_ZERO(&fdRead);
FD_SET(m_sock, &fdRead);
do
{
ret = ::select(0, &fdRead, NULL, NULL, &TimeOut);
if (ret == SOCKET_ERROR)
break;
if (ret > 0)
{
if (nLeft == 0)
ret = ::recv(m_sock, pBuffer, sizeof(PACKHEADER), 0);
else
ret = ::recv(m_sock, pBuffer + idx, nLeft, 0);
if (ret == 0) //对方连接中断
ret = SOCKET_ERROR;
if (ret == SOCKET_ERROR)
break;
if (nLeft == 0)
nLeft = pHead->length;
else
nLeft -= ret;
idx += ret;
}
else
break;
}
while (nLeft > 0);
PACKHEADER定义struct PACKHEADER{char from[NAMELEN]; //发动端标识char to[NAMELEN]; //接收端标识int type; //包命令类型int length; //包长度, };
参考
阅读(1020) | 评论(0) | 转发(0) |