套接字是否应该与Python中的select一起工作?(Should sockets be non

编程入门 行业动态 更新时间:2024-10-25 23:30:52
套接字是否应该与Python中的select一起工作?(Should sockets be non-blocking to work with select in Python?) 在使用Python中的select.select时套接字是否应该设置为非阻塞? 如果它们是或者不是,它们会有什么不同?

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

Should sockets be set to non-blocking when used with select.select in Python? What difference does it make if they are or aren't?

Occasionally I find that calling send on a socket that returns sendable will block. Furthermore I find that blocking sockets will generally send the whole buffer given (128 KiB). In non-blocking mode, sending will accept far fewer bytes (20-40 KiB compared with the example given earlier) and return quicker. I'm using Python 3.1 on Lucid.

最满意答案

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

我没有意识到在select中阻塞/非阻塞套接字的不同,但在linux上, select系统调用手册页在'BUGS'部分有这个:

在Linux下,select()可能会报告套接字文件描述符为“准备好读取”,而后续的读取块。 例如,这可能发生在数据到达但检查错误校验和并被丢弃时发生。 在其他情况下,文件描述符被虚假地报告为就绪。 因此,在不应阻塞的套接字上使用O_NONBLOCK可能更安全。

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

至于阻塞写发送更多的数据,这是预期的。 send将阻塞,直到有足够的缓冲区空间在套接字阻塞时传递整个请求。 如果套接字是非阻塞的,它只会发送尽可能多的套接字发送缓冲区。

The answer might be OS dependent unfortunately. I'm replying only regarding Linux.

I'm not aware of differences regarding blocking/non-blocking sockets in select, but on linux, the select system call man page has this in it 'BUGS' section:

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.

I doubt a python abstraction above that could "hide" this issue without side-effects.

As for the blocking write sending more data, that's expected. send will block until there is enough buffer space to pass your whole request down if the socket is blocking. If the socket is non-blocking, it only sends as much as can currently fit in the socket's send buffer.

更多推荐

本文发布于:2023-08-04 20:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1421399.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:工作   Python   select   sockets

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!