I was trying through looping around ioctlselect
or recv
, which is consuming time. Somebody suggested to use select
. select
is very fast. But problem is i should receive only after more than one byte is ready to be received. select
is ready if one byte is also readable from the socket. Are there any alternatives?
Asked
Active
Viewed 320 times
0

Björn Pollex
- 75,346
- 28
- 201
- 283

Ershad
- 947
- 2
- 20
- 40
-
Same question as http://stackoverflow.com/questions/3926341/determing-the-number-of-bytes-ready-to-be-recvd – Basile Starynkevitch Nov 30 '11 at 09:39
1 Answers
2
Use select
, and put the socket in non-blocking mode. (See fcntl
, it can do this for you.) Then, simply recv
into a large buffer. If there is less data available, you'll get a short recv
, and recv
will return to you the number of bytes it read. If nothing is available, recv
will fail, and errno
will be EWOULDBLOCK
or EAGAIN
(check for both).
recv
can fail with EAGAIN
/EWOULDBLOCK
even if select
says data is available.
It is more efficient and easier to read as much as available, and then buffer in your code as needed.
Edit: oops, you're on Windows. Same idea, except you'll need to check Winsock's error codes, not errno
, and ioctlsocket
can put the socket in non-blocking mode. (I'm not sure if Windows has fcntl
or not.)

Thanatos
- 42,585
- 14
- 91
- 146