针对链接(connect)时候的超时:
# 法一:
import socket
socket.setdefaulttimeout(5)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
sock.sendall('xxx')
sock.recv(1024)
sock.close()
'''
20160716 update
socket.setdefaulttimeout(5) 此句必须放到建立链接的前面,否则超时设置无效果
'''
# 法二:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
sock.connect((host, port))
# 恢复默认超时设置,设置某些情况下socket进入阻塞模式(如makefile)
sock.settimeout(None)
sock.connect((host, port))
sock.sendall('xxx')
sock.recv(1024)
sock.close()
针对接收(recv)数据时的超时:
# 法一:
import socket
socket.setdefaulttimeout(5)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
sock.sendall('xxx')
# 连接和接收的时候都设置一次超时
sock.settimeout(5)
sock.recv(1024)
sock.close()
# 法二[未验证]:
import select
mysocket.setblocking(0)
ready = select.select([mysocket], [], [], timeout_in_seconds)
if ready[0]:
data = mysocket.recv(4096)
来源:CSDN
作者:whatday
链接:https://blog.csdn.net/whatday/article/details/104059531