如何在python的套接字接收方法上设置超时? [英] How to set timeout on python's socket recv method?

查看:73
本文介绍了如何在python的套接字接收方法上设置超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 python 的 socket recv 方法上设置超时.怎么做?

I need to set timeout on python's socket recv method. How to do it?

推荐答案

典型的做法是使用 select() 等待数据可用或超时发生.仅在数据实际可用时调用 recv().为了安全起见,我们还将套接字设置为非阻塞模式以保证 recv() 永远不会无限期地阻塞.select() 也可用于一次等待多个套接字.

The typical approach is to use select() to wait until data is available or until the timeout occurs. Only call recv() when data is actually available. To be safe, we also set the socket to non-blocking mode to guarantee that recv() will never block indefinitely. select() can also be used to wait on more than one socket at a time.

import select

mysocket.setblocking(0)

ready = select.select([mysocket], [], [], timeout_in_seconds)
if ready[0]:
    data = mysocket.recv(4096)

如果你有很多打开的文件描述符,poll()select() 的更有效替代方法.

If you have a lot of open file descriptors, poll() is a more efficient alternative to select().

另一种选择是使用 socket.settimeout() 为套接字上的所有操作设置超时,但我看到您在另一个答案中明确拒绝了该解决方案.

Another option is to set a timeout for all operations on the socket using socket.settimeout(), but I see that you've explicitly rejected that solution in another answer.

这篇关于如何在python的套接字接收方法上设置超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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