Set timeout for Python socket when sending data out -


i set timeout python socket client. means, socket client connects server sends data within 1 second. if takes more 1 second, method raise kind of exception or error.

here source code:

def senddatatelnet(iptmp, strtmp):     # try send data <iptmp>     try:         s = socket.socket(socket.af_inet, socket.sock_stream)         writelog("connecting %s" % (iptmp))         s.settimeout(1.0)         s.connect((iptmp, 4242))         writelog("connected %s, start send data" % (iptmp))         s.sendall(strtmp)         s.close()         s = none         writelog("done writing %s" % (iptmp))         return true      except socket.timeout:         writelog("timed out when connecting %s" % (iptmp))         s.close()         s = none         return false      except socket.error:         writelog("error when communicating %s" % (iptmp))         s.close()         s = none         return false 

this doesn't work me. works when "connect" action takes longer 1 second. however, if connects fine sends large amount of data takes more 1 second, no exception raised.

you set alarm timeout prior socket call , 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)     # code  .... except timeouterror:     print "timeout reached" finally:     signal.alarm(0) 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -