简体   繁体   中英

Can a socket be made non-blocking only for the recv() function?

I want to be able to call recv() without having to block, so I want to make it non-blocking, but I do not want it to be non blocking when sending data. So can a socket be made non-blocking only for the recv() function, or does the blocking/non-blocking mode affects all of the socket functions?

For windows, you can use ioctlsocket() to set the socket in non-blocking mode. Unfortunately these settings apply to all operations on the socket. So for your case you'll have to switch it between the receivings and the sendings.

For the records: For linux, you could have used the MSG_DONTWAIT flag in the recv() call arguments. The single call will then be non blocking.

There is no way to make the socket non-blocking just for the recv() function.

However there is something close to that (but flawed), which is by using ioctlsocket() with the FIONREAD flag. For example:

unsigned long l;
ioctlsocket(s, FIONREAD, &l);

This function will return (immediately without blocking) how many bytes is available to be read, although not quite accurate (but we don't care about that, because we are using it to know if there is data to be read and not to know exactly how many bytes are there).

As I have mentioned earlier, this approach is flawed, because it doesn't tell you when the other end has disconnected, because recv() returns 0 on disconnect, and this function will return 0 if no data is available!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM