发送数据时为 Python 套接字设置超时

Set timeout for Python socket when sending data out

我想为 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

这对我不起作用。它仅在 "connect" 操作时间超过 1 秒时有效。但是,如果连接正常但发送大量数据需要超过 1 秒,则不会引发异常。

您可以在套接字调用之前设置警报超时 完成后清除。

例如

import os, signal

class TimeoutError(Exception):
    pass

def handle_timeout(signum, frame):
    import errno
    raise TimeoutError(os.strerror(errno.ETIME))

TIMEOUT=1

signal.signal(signal.SIGALRM, handle_timeout)
signal.alarm(TIMEOUT)

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # your code  ....
except TimeoutError:
    print "Timeout reached"
finally:
    signal.alarm(0)