为什么recv收到的数据不对?
我自己写的socket程序,用C++builder 5编译。程序如下:unsigned char csWinEthDri::Initialize(char *ip)
{
struct sockaddr_in serv_addr;
int socket_size,nZero;
WSADATA wsaData;
if(m_socked_fd>0)
return 0;
if(WSAStartup(0x101,&wsaData))
return ERROR_CON_SOCKETINIT;
if((m_socked_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
return ERROR_CON_SOCKETINIT;
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(CON_SOCK_NUM);
serv_addr.sin_addr.s_addr = inet_addr(ip);
#if 0
socket_size = bind(m_socked_fd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr));
if(socket_size == -1)
{
CloseSock();
return ERROR_CON_SOCKETBIND;
}
#endif
memset(&(serv_addr.sin_zero),0,sizeof(serv_addr.sin_zero));
if(connect(m_socked_fd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1)
{
CloseSock();
return ERROR_CON_SOCKETCON;
}
//setsockopt(m_socked_fd,IPPROTO_TCP,TCP_NODELAY,(char *)&nZero,sizeof(nZero));
return 0;
}
unsigned int csWinEthDri::TsockCmd(char * pCmdBuf, unsigned int lengh, unsigned char read)
{
int retval,retry;
retval = send(m_socked_fd, pCmdBuf, lengh, 0);
Sleep(1); //sleep to make sure send out data
if(retval == -1) return 0;
if(read)
{
retry = 0;
while(1)
{
struct sockaddr_in c_addr;
int addr_len;
addr_len = sizeof(c_addr);
memset(pCmdBuf,0,lengh);
Sleep(1); //sleep to make sure get data
retval = recvfrom(m_socked_fd, pCmdBuf, MAX_BUF, 0, (struct sockaddr *) &c_addr, &addr_len);
if(retval == -1) return 0;
else if(retry == 10000) {
return 0 ;
}
else if(pCmdBuf[0]==TP_ACKRD) {
if(pCmdBuf[retval-1]==TP_ACKRD)
break;
else retry++;
}
else retry++;
//break;
}
}
return 1;
}
server端跑在linux下,我确定server端发送的数据都是对的。
接收端遇到的情况是:
比如发送端发送了3笔数据:
0x01,0x02,0x03,0x04
0x04,0x05,0x06,0x07
0x07,0x08,0x09,0x0A
我的接收总是有问题,第一次调用recv接收倒 0x01,0x02,0x03,0x04
第二次调用recv,还是接收到0x01,0x02,0x03,0x04
第三次调用recv,才能接收到0x04,0x05,0x06,0x07
...
非常奇怪。
本来我的代码在接收不同size的时候也有问题,后来我加了包头包尾,这样就避免在size不一样的时候出错。
问题是
感觉recv从接收缓存受到数据后不会把接收缓存清空,所以再次调用recv的时候还是收到了上一次数据。
怎么觉得这个问题呢?