Reputation: 5649
MSDN provides following code:
int iResult;
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
} while( iResult > 0 );
iResult store the number of bytes received! In my case I can't do it like this because the receive hangs if nothing was received (or end was reached) -> so the exit condition never match!
Something wrong and/or why the recv hangs here?
Greets
Upvotes: 0
Views: 587
Reputation: 310850
the receive hangs if nothing was received
Correct.
(or end was reached)
Incorrect. It returns zero under that circumstance. However 'end is reached' means that the peer has closed the connection. Possibly you have some other definition in mind?
I suspect your problem is that the peer isn't closing the connection and you are still expecting a zero. It doesn't work that way.
Upvotes: 0
Reputation: 2057
Actually, if there no incoming data is available at the socket, the recv blocks till data arrive. You can use select() to determine when more data arrives and then use recv() to read it.
Upvotes: 0
Reputation: 409136
It's because sockets are, by default, blocking. This means that calls to e.g. recv
will block until something is received. You can use the ioctlsocket
function to make the socket non-blocking.
You do have to be prepared that recv
can return with an WSAEWOULDBLOCK
error if nothing is available to be received. Or use polling functions such as select
to know when you have data that can be received. If you don't want to poll, search for "asynchronous sockets" on MSDN to find both server and client examples.
Upvotes: 3