有时候,tcp socket一定要接收到指定的字节数才算符合预期,那怎么实现呢?
在很多网络编程的书中都有介绍,一起来看看(一直循环接受,达标为止):
- int recvLength(char *sRecvBuffer, size_t iRecvLen)
- {
- int iRet = checkSocket();
- if(iRet < 0)
- {
- return iRet;
- }
-
- size_t iRecvLeft = iRecvLen;
- iRecvLen = 0;
-
- TC_Epoller epoller(false);
- epoller.create(1);
- epoller.add(_socket.getfd(), 0, EPOLLIN);
-
- while(iRecvLeft != 0)
- {
- int iRetCode = epoller.wait(_timeout);
- if (iRetCode < 0)
- {
- _socket.close();
- return EM_SELECT;
- }
- else if (iRetCode == 0)
- {
- _socket.close();
- return EM_TIMEOUT;
- }
-
- epoll_event ev = epoller.get(0);
- if(ev.events & EPOLLIN)
- {
- int len = _socket.recv((void*)(sRecvBuffer + iRecvLen), iRecvLeft);
- if (len < 0)
- {
- _socket.close();
- return EM_RECV;
- }
- else if (len == 0)
- {
- _socket.close();
- return EM_CLOSE;
- }
-
- iRecvLeft -= len;
- iRecvLen += len;
- }
- else
- {
- _socket.close();
- return EM_SELECT;
- }
- }
-
- return EM_SUCCESS;
- }