问题描述
- recv返回值问题和在while(recv())的返回值不一样
-
if ((select(sockfd + 1), &readfd, NULL, NULL, &stime) > 0) { #if 1 nlen = recv(sockfd, pcBuffer, 199, 0); printf("recv num(%d), buffer num(%d). ", nlen, lRecvnum); if ((lRecvnum + nlen) < 199) { lRecvnum += nlen; pcBuffer += nlen; printf("recv num(%d), buffer num(%d), buffer(%s). ", nlen, lRecvnum, buf); } #else while ((nlen = recv(sockfd, pcBuffer, 199, 0)) > 0) { printf("recv num(%d), buffer num(%d). ", nlen, lRecvnum); if ((lRecvnum + nlen) < 199) { Recvnum += nlen; pcBuffer += nlen; printf("recv num(%d), buffer num(%d), buffer(%s). ", nlen, lRecvnum, buf); } } #endif }
现在想问的是执行上面一段代码,就是#if 1,recv返回的值是正常的,返回值是199跟写到pcBuffer的数据是一样的,但是如果把#if 1改成#if 0,执行下面在
while ((nlen = recv(sockfd, pcBuffer, 199, 0)) > 0)的代码分支的时候,recv的返回值一直是1,但是写到pcBuffer的数据却是正确的,这个是为什么?recv的返回值是1,但是写到pcBuffer中的个数却不是1,而是正确的个数,为什么这个时候的recv不返回不跟#if 1的时候是一样的,也是199?
解决方案
按正确的逻辑
while ((nlen = recv(sockfd, pcBuffer, 199, 0)) > 0)这个应该改为
Recvnum = 0;
while ((nlen = recv(sockfd, pcBuffer, 199- Recvnum, 0)) <199)
{
}
解决方案二:
标准输入cin的返回值以及while(cin>>x)的问题
解决方案三:
tf("recv num(%d), buffer num(%d).
", nlen, lRecvnum);
if ((lRecvnum + nlen) < 199)
{
lRecvnum += nlen;
pcBuffer += nlen;
printf("recv num(%d), buffer num(%d), buffer(%s).
", nlen, lRecvnum, buf);
}
#else
while ((nlen = recv(sockfd, pcBuffer, 199, 0)) > 0)
{
printf("recv num(%d), buffer num(%d).
", nlen, lRecvnum);
if ((lRecvnum + nlen) < 199)
解决方案四:
tf("recv num(%d), buffer num(%d).
", nlen, lRecvnum);
if ((lRecvnum + nlen) < 199)
{
lRecvnum += nlen;
pcBuffer += nlen;
printf("recv num(%d), buffer num(%d), buffer(%s).
", nlen, lRecvnum, buf);
}
#else
while ((nlen = recv(sockfd, pcBuffer, 199, 0)) > 0)
{
printf("recv num(%d), buffer num(%d).
", nlen, lRecvnum);
if ((lRecvnum + nlen) < 199)