在 Python 套接字上连接失败时正确设置超时
Set correctly timeout when connection fails on Python socket
我开始学习 python 套接字和 TCP/IP 模型,所以我才刚刚开始。我有一段简单的代码可以按预期正常工作:
import socket
from datetime import datetime
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
start = datetime.now()
try:
s.connect(("www.whosebug.com", 80))
s.close()
except Exception as e:
print "Error : ", e
print datetime.now() - start
在这种情况下它工作正常,但如果我更改端口并使用另一个端口,例如 81(仅用于测试),套接字不会连接(如预期的那样)。
但在执行打印语句(最后一行)之前,我必须等待或多或少 20 秒。
我想了解如何让它更快,所以当连接失败或端口关闭时,我收到一个响应错误,我不会等待那么多时间。
另外我想了解为什么它有这种行为,以及如何正确设置超时。
可能这是一个新手问题,但您的所有回复和建议将不胜感激。
非常感谢。
使用socket.settimeout()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1.0)
这会将超时设置为 1 秒。
socket.settimeout(value)
Set a timeout on blocking socket operations. The value argument can be a nonnegative float expressing seconds, or None. If a float is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. Setting a timeout of None disables timeouts on socket operations. s.settimeout(0.0) is equivalent to s.setblocking(0); s.settimeout(None) is equivalent to s.setblocking(1).
我开始学习 python 套接字和 TCP/IP 模型,所以我才刚刚开始。我有一段简单的代码可以按预期正常工作:
import socket
from datetime import datetime
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
start = datetime.now()
try:
s.connect(("www.whosebug.com", 80))
s.close()
except Exception as e:
print "Error : ", e
print datetime.now() - start
在这种情况下它工作正常,但如果我更改端口并使用另一个端口,例如 81(仅用于测试),套接字不会连接(如预期的那样)。 但在执行打印语句(最后一行)之前,我必须等待或多或少 20 秒。 我想了解如何让它更快,所以当连接失败或端口关闭时,我收到一个响应错误,我不会等待那么多时间。 另外我想了解为什么它有这种行为,以及如何正确设置超时。 可能这是一个新手问题,但您的所有回复和建议将不胜感激。 非常感谢。
使用socket.settimeout()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1.0)
这会将超时设置为 1 秒。
socket.settimeout(value)
Set a timeout on blocking socket operations. The value argument can be a nonnegative float expressing seconds, or None. If a float is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. Setting a timeout of None disables timeouts on socket operations. s.settimeout(0.0) is equivalent to s.setblocking(0); s.settimeout(None) is equivalent to s.setblocking(1).