================
收藏備用。
================
參數解釋: sck - socket buf - 接收緩衝區 size-緩衝區大小 time_out-等待時間(按秒計)若是超時則返回 返回值:收到字節數,0表示超時等錯誤
int rcv(int sck, void * buf, int size, int time_out)
socket
{
code
if (sck < 1 || !buf || size < 1) return 0;
select
timeval tv = { 0, 0}; timeval * ptv = 0;
im
if (time_out > 0) { tv.tv_sec = time_out; ptv = &tv; }
error
memset(buf, 0, size);
時間
int r = 0; char * b = (char*) buf; int sz = size;
while
fd_set rd, er; int total = 0; time_t t0 = time(0); time_t t1 = 0;
co
do {
time
FD_ZERO(&rd); FD_SET(sck, &rd);
錯誤
FD_ZERO(&er); FD_SET(sck, &er);
r = select(sck + 1, &rd, 0, &er, ptv);
if (r == -1) { nperror("select()"); return -1; }
if (FD_ISSET(sck, &er)) {
nperror("socket(shutdown)"); return -1;
}//end if
if (FD_ISSET(sck, &rd)) {
r = recv(sck, b, sz, 0);
if (r == -1) { nperror("recv()"); return -1; }
total += r; sz -= r; b+= r;
}//end if
if (time_out > 0)
t1 = time(0) - t0;
else
t1 = time_out - 1;
//end if
}while(sz && t1 < time_out);
return total;
}//end if