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

时间:2015-07-30 08:02:30

标签: python python-sockets

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

这对我不起作用。它仅适用于&#34; connect&#34;行动需要超过1秒。但是,如果连接正常但发送的大量数据需要1秒以上,则不会引发异常。

1 个答案:

答案 0 :(得分: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)