Socket recv()以前進行select代碼

================
收藏備用。
================
參數解釋:
sck - socket
buf - 接收緩衝區
size-緩衝區大小
time_out-等待時間(按秒計)若是超時則返回
返回值:收到字節數,0表示超時等錯誤
 
  1. int rcv(int sck, void * buf, int size, int time_out)socket

  2. {code

  3. if (sck < 1 || !buf || size < 1) return 0;select

  4. timeval tv = { 0, 0}; timeval * ptv = 0;im

  5. if (time_out > 0) { tv.tv_sec = time_out; ptv = &tv; }error

  6. memset(buf, 0, size);時間

  7. int r = 0; char * b = (char*) buf; int sz = size;while

  8. fd_set rd, er; int total = 0; time_t t0 = time(0); time_t t1 = 0;co

  9. do {time

  10. FD_ZERO(&rd); FD_SET(sck, &rd);錯誤

  11. FD_ZERO(&er); FD_SET(sck, &er);

  12. r = select(sck + 1, &rd, 0, &er, ptv);

  13. if (r == -1) { nperror("select()"); return -1; }

  14. if (FD_ISSET(sck, &er)) {

  15. nperror("socket(shutdown)"); return -1;

  16. }//end if

  17. if (FD_ISSET(sck, &rd)) {

  18. r = recv(sck, b, sz, 0);

  19. if (r == -1) { nperror("recv()"); return -1; }

  20. total += r; sz -= r; b+= r;

  21. }//end if

  22. if (time_out > 0)

  23. t1 = time(0) - t0;

  24. else

  25. t1 = time_out - 1;

  26. //end if

  27. }while(sz && t1 < time_out);

  28. return total;

  29. }//end if

相關文章
相關標籤/搜索