End of the recv () loop when all information is read using Winsock

I have a problem in my recv () loop for winsock. I try to end the loop when iResult == 0, however the loop only ends after the socket is closed. It seems to be hanging on the very last recv (), where iResult will be 0. So, any ideas on how to effectively complete the loop? My ultimate goal (whether iResult == 0 or not, maybe I'm doing it wrong) is to stop the loop when all the information sent has been read. Here is a loop.

do { iResult = recv(socket, recvbuf, BUFLEN-1, 0); if(iResult > 0){ // Null byte :) // Remove that garbage >:( recvbuf[iResult] = '\0'; printf("Recvbuf: %s\n\n\niResult: %d\n",recvbuf,iResult); continue; // working properly } else if(iResult == 0) // Connection closed properly break; else { printf("ERROR! %ld",WSAGetLastError()); break; } } while(iResult > 0); 

As I said, I get all the data, I just can not exit the loop. The next step is to write data to the server, but it hangs here until the ping timeout. Socket SOCK_STREAM and BUFLEN are defined as 0x200

thanks

+6
c ++ windows winapi winsock recv
source share
2 answers

By default, instead of returning 0, recv blocks if there is no data to receive :

If the incoming data is not available in the socket, the call blocks are recv and expects to receive data in accordance with the blocking rules defined for WSARecv with the MSG_PARTIAL flag set if the socket is not blocked. In this case, the SOCKET_ERROR value is returned with the error code set for WSAEWOULDBLOCK. Choosing whether the WSAAsyncSelect or WSAEventSelect functions can be used to determine when more data is being received.

You can use ioctlsocket to put a socket in non-blocking mode:

 u_long iMode = 1; ioctlsocket(socket, FIONBIO, &iMode); 

EDIT : here's the setsockopt sentence that I made in an earlier rev, then deleted (see comments):

You can use setsockopt with the SO_RCVTIMEO option to set the socket timer on recv if no data is available.

+4
source share

When designing a TCP communications mechanism, you must define message boundaries. (often \ r \ n). Tcp itself knows no bounds; you have to do it yourself. A call to recv () may not always return at the message boundary. One send () can be split into several recv () - s at the other end.

+1
source share

All Articles