python - 套接字应该是非阻塞的以便在 Python 中使用 select 吗?

标签 python sockets select python-3.x blocking

  1. select.select一起使用时,套接字是否应设置为非阻塞?在 Python 中?
  2. 它们是否存在有什么区别?

偶尔我发现调用send在返回可发送的套接字上将阻塞。此外,我发现 blocking套接字通常会发送给定的整个缓冲区 (128 KiB)。在非阻塞模式下,发送将接受更少的字节(与前面给出的示例相比为 20-40 KiB)并且返回更快。我正在使用 Python 3.1 on Lucid .

最佳答案

不幸的是,答案可能取决于操作系统。我只回答关于 Linux 的问题。

我不知道 select 中关于阻塞/非阻塞套接字的区别,但在 linux 上,select 系统调用手册页的“BUGS”部分有这个:

Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. This could for example happen when data has arrived but upon examination has wrong checksum and is discarded. There may be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use O_NONBLOCK on sockets that should not block.

我怀疑上面的 python 抽象是否可以“隐藏”这个问题而没有副作用。

至于发送更多数据的阻塞写入,这是意料之中的。如果套接字阻塞,send 将阻塞,直到有足够的缓冲区空间来传递您的整个请求。如果套接字是非阻塞的,它只会发送当前适合套接字发送缓冲区的数据。

关于python - 套接字应该是非阻塞的以便在 Python 中使用 select 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5237733/

相关文章:

python - 查找给定日期的季度结束日期, Pandas

sockets - 如何使用 Nginx/Openresty 将 tcp 流复用到多个 websocket 客户端?

javascript - 无法访问脚本中 ColdFusion 标记中的 JavaScript 变量

MySQL查询,其中一列行的结果与下一列相加

c# - C#.NET客户端和C服务器之间的套接字编程

javascript - 如何仅在选择两个下拉菜单时触发事件?

python - 使用 'all()' 函数在 IF 语句中进行多个 bool 测试

python - 支持向量回归在线学习

Python 和 Ctypes 填充结构数组

c - 网络链接套接字