Python套接字连接超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3432102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python socket connection timeout
提问by anonymous
I have a socket that I want to timeout when connecting so that I can cancel the whole operation if it can't connect yet it also want to use the makefile for the socket which requires no timeout.
我有一个套接字,我想在连接时超时,以便在无法连接的情况下取消整个操作,但它还想将 makefile 用于不需要超时的套接字。
Is there an easy way to do this or is this going to be a difficult thing to do?
有没有简单的方法可以做到这一点,或者这将是一件困难的事情?
Does python allow a reset of the timeout after connected so that I can use makefile and still have a timeout for the socket connection
python 是否允许在连接后重置超时,以便我可以使用 makefile 并且仍然有套接字连接的超时
回答by Jo?o Pinto
You just need to use the socket settimeout()method before attempting the connect(), please note that after connecting you must settimeout(None)to set the socket into blocking mode, such is required for the makefile .
Here is the code I am using:
您只需要settimeout()在尝试之前使用 socket方法connect(),请注意,连接后您必须settimeout(None)将 socket 设置为阻塞模式,这是 makefile 所必需的。这是我正在使用的代码:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)
回答by John La Rooy
If you are using Python2.6 or newer, it's convenient to use socket.create_connection
如果你使用的是Python2.6或更新版本,使用起来很方便 socket.create_connection
sock = socket.create_connection(address, timeout=10)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)
回答by Himanshu Kanojiya
For setting the Socket timeout, you need to follow these steps:
要设置 Socket 超时,您需要按照以下步骤操作:
import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.settimeout(10.0)

