polling a socket and receiving data [previously titled as 'ioctlsocket']

Started by
12 comments, last by Todo 16 years, 10 months ago
WinSock doesn't care where the buffer is coming from; it just wants an array of bytes to write into. '&vector[0]' is as good as '&stackvar' or 'mallocblock'.

However, the original question was: how do I know how much to read?

The answer is that you should try to read as much as possible in the first recv() call. 256 bytes is typically way too little. Try 65k at a time. When select() returns that there is data, the very next call to recv() is guaranteed to not block, even if the socket is blocking. That's because the specification for recv() is that the call may return a smaller amount of data than requested, if that's what it has to do to avoid blocking. recv() on a blocking socket only blocks if there is no data in the buffer when you call recv().

Btw: instead of using memcpy() to put things at the end of a vector, you can use insert.
enum Bool { True, False, FileNotFound };
Advertisement
Yeah, I'm [ab]using the fact that vectors are guaranteed to be contiguous [smile]

Quote:Original post by hplus0603
The answer is that you should try to read as much as possible in the first recv() call. 256 bytes is typically way too little. Try 65k at a time. When select() returns that there is data, the very next call to recv() is guaranteed to not block, even if the socket is blocking. That's because the specification for recv() is that the call may return a smaller amount of data than requested, if that's what it has to do to avoid blocking. recv() on a blocking socket only blocks if there is no data in the buffer when you call recv().

Btw: instead of using memcpy() to put things at the end of a vector, you can use insert.
Do you really think 65k is nessecary? I can see why you'd want to (To make sure the socket buffer gets emptied ASAP), but 64k is too big to have on the stack isn't it? I suppose it could be a static buffer, or allocated with new.

About the memcpy(), I was aware of insert, but I'm still not comfortable using pointers as iterators for some reason. And I would have thought memcpy() would be faster (Admittedly, probably not with a 256 byte buffer)
It's hard to make speed of CPU matter much in networking.
Your DSL modem gives you, what, 160 kB per second?
Modern memory bandwidth is 12 GB/s, for about 5 orders of magnitude difference :-)

std::vector is guaranteed to be contiguous, just so that you can use them as buffers.
enum Bool { True, False, FileNotFound };
And, as a plus, pointers are iterators :-). More so, iterators are a generalization of pointers. So, pointers are iterators, but not all iterators are pointers!

This topic is closed to new replies.

Advertisement