0

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.

duong_dajgja
  • 4,196
  • 1
  • 38
  • 65

1 Answers1

2

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)
harryr
  • 106
  • 5
  • I also considered this solution. However, when I checked the log file this morning, I found out that there was one time the timeout exception was not raised. This was in the log: "connecting to 10.0.0.13; connected to 10.0.0.13, start to send data". There was nothing about timeout reached or done writing data... – duong_dajgja Jul 31 '15 at 06:42