WSock32 recv(..., size ) question

Started by
2 comments, last by Anon Mike 16 years, 10 months ago
So I was re-visiting some old code that involved networking and I just recently fixed a bug with one of our client-server communications. It came from the fact that when I call recv(.., size) on the socket, it doesn't always wait to receive that full amount in 'size' I had encountered this in the past, so I wrote a while loop that kept calling recv( ) and checking the number of bytes it returned, and making sure to 'finish' when it reached the size amount. Is there a reason why the sockets in windows don't return the full size on a single recv call? I remember doing this in my networking class, and on Unix - it didn't have this problem. Only with winsock did I have to do the while loop. Something I'm missing or forgetting? (wsock32.lib btw - for the version)
Advertisement
Consider this:

Server waits to recv(1024).

Client sends 500 bytes, then waits for response from server.

Server waits for 1024 bytes that will never arrive.

Unless you used some convenience API, I strongly doubt you were actually able to read x ammount of bytes from network with low level APIs - for the reason listed above.

You either didn't handle the error conditions and were lucky enough for everything to work out, or you used some already provided function that did that for you.

Then again, Unixes can be funny, so I can't guarantee that it wasn't the case.
Glucose, the behavior of recv() that you observed is actually the same on both windows and unix. By default, recv() may return less than the passed in buffer size, so any code that expects a specific minimum number of bytes will have to have a loop (or set specific flags). There are platform-specific flags that you can pass in to instruct recv() to wait until all "requested" bytes are available (or an error/signal/etc. occurs, of course). Regarding your networking class, either you had the right flags set or your sender/data/network conditions were such that the entire packet was available in the socket buffer when you went to read it, i.e. you were lucky. :)

Of course, the exact behavior of recv() depends on whether you're using udp or tcp, whether your socket is blocking/non-blocking, what flags you pass in, etc. For windows, this stuff is well-documented on MSDN. Check out the docs for recv() for the details.
This is one of those things people usually discover when they start talking over the actual wild & woolly Internet. When you have an app talking to itself on the same box or at most a LAN things tend to work perfectly - no lag, everything is fast, buffers never get full, packets never go astray or reorder themselves, etc, etc.

Like cwilson says, this is normal. If you check your *nix man page it'll say something along the lines of "returns the number of bytes received", which implies that you could receive less than you asked for.
-Mike

This topic is closed to new replies.

Advertisement