本文接着上篇分包收包问题隶属同一个问题。今天刚遇到的问题并解决了,TCP协议传输,流式套接字编程,收取网络数据时,从缓冲数据中读取出应用层完整包,原来没有单个固定头长度的数据包取出bug表现,现在后来加入一个只有头的报文进入,于是整个取包就出现混乱。完整性再一次无法愈合。现在重新整理取包流程。msglen = recv(s, buffer, sizeof(buffer), 0); buf4packet 为存储完整数据包的临时数据缓冲区
while(msglen>0)
{
{
int len,szcpy;
len = (offset < sizeof(COMM_HEAD) ? sizeof(COMM_HEAD): ((COMM_HEAD*)buf4packet)->msg_len);
szcpy = len - offset;
szcpy = (msglen > szcpy ? szcpy:msglen);
memcpy(buf4packet + offset, buffer2, szcpy);
offset += szcpy;
buffer2 += szcpy;
msglen -= szcpy;
if (offset < sizeof(COMM_HEAD)) continue;
len = ((COMM_HEAD*)buf4packet)->msg_len;
if (offset <len) continue;
if (offset !=len)
{
xlog_out(LOG_COM,P_FATAL,"message_recv occur an error on packet completeness analyse!\n");
close(s);
break;
}
}
offset = 0;
COMM_HEAD* msg_p = NULL;
msg_p = message_parse(buf4packet);
if (msg_p != NULL)
{
……
}
……
}