duong_dajgja
duong_dajgja

Reputation: 4276

Set timeout for Python socket when sending data out

I would like to set timeout for Python socket client. That means, socket client connects to server then sends data within 1 second. If it takes more than 1 second, the method would raise some kind of exception or error.

Here is my source code:

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

This doesn't work for me. It works only when "connect" action takes longer than 1 second. However, if it connects fine but it sends large amount of data that takes more than 1 second, no exception raised.

Upvotes: 1

Views: 6675

Answers (1)

harryr
harryr

Reputation: 126

You could set an alarm timeout prior to the socket call and clear when done.

eg.

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)

Upvotes: 2

Related Questions