我想为 Python 套接字客户端设置超时。这意味着,套接字客户端连接到服务器然后在 1 秒内发送数据。如果花费超过 1 秒,该方法将引发某种异常或错误。
这是我的源代码:
def sendDataTelnet(ipTmp, strTmp):
# try to send data to <ipTmp>
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
writeLog("connecting to %s" % (ipTmp))
s.settimeout(1.0)
s.connect((ipTmp, 4242))
writeLog("connected to %s, start to send data" % (ipTmp))
s.sendall(strTmp)
s.close()
s = None
writeLog("done writing to %s" % (ipTmp))
return True
except socket.timeout:
writeLog("timed out when connecting to %s" % (ipTmp))
s.close()
s = None
return False
except socket.error:
writeLog("error when communicating with %s" % (ipTmp))
s.close()
s = None
return False
这对我不起作用。它仅在“连接”操作时间超过 1 秒时才有效。但是,如果它连接良好但发送大量数据需要超过 1 秒,则不会引发异常。