我有一个套接字,我想超时时,我可以取消整个操作,如果它不能连接,但它也想使用生成文件的套接字,不需要超时。
有没有一个简单的方法来做到这一点,还是这将是一个困难的事情去做?
Python 是否允许在连接后重置超时,以便我可以使用 makefile 并仍然为套接字连接设置超时
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()
connect()
settimeout(None)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(10) sock.connect(address) sock.settimeout(None) fileobj = sock.makefile('rb', 0)
If you are using Python2.6 or newer, it's convenient to use socket.create_connection
socket.create_connection
sock = socket.create_connection(address, timeout=10) sock.settimeout(None) fileobj = sock.makefile('rb', 0)
For setting the Socket timeout, you need to follow these steps:
import socket socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socks.settimeout(10.0) # settimeout is the attr of socks.
Try this code:
try: import socket socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) socket.settimeout(10) except socket.error: print("Nope !!!")