只能为 recv() 函数使套接字成为非阻塞的吗? [英] Can a socket be made non-blocking only for the recv() function?

查看:43
本文介绍了只能为 recv() 函数使套接字成为非阻塞的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够调用 recv() 而不必阻塞,所以我想让它非阻塞,但我不希望它在发送数据时非阻塞.那么,可以使套接字仅对 recv() 函数进行非阻塞,还是阻塞/非阻塞模式会影响所有套接字函数?

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?

推荐答案

没有办法仅针对 recv() 函数使套接字非阻塞.

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

然而,有一些接近的东西(但有缺陷),即使用带有 FIONREAD 标志的 ioctlsocket().例如:

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).

正如我之前提到的,这种方法是有缺陷的,因为它不会告诉您另一端何时断开连接,因为 recv() 在断开连接时返回 0,如果没有可用数据,此函数将返回0

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!

这篇关于只能为 recv() 函数使套接字成为非阻塞的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆