I set up a timer in the socket. If it hasn't received any connection requests in 30 seconds, the program finishes. Anyway, I'd like to print those 30 seconds into stdout as a timer, so that the user can see how much seconds are left. If there's a connection request before the timer expires, I'd like to stop the timer and keep executing the code as if nothing had happened. Any help? This is a fragment of my code:
while True:
try:
s_TCP.settimeout(30)
print ("Waiting for a connection...")
s_TCP.listen(1)
#I'd like to set the timer here
connection, addr= s_TCP.accept()
print ("\nConnection established")
except socket.timeout:
print ("Timer expired")
s_TCP.close()
sys.exit()
except socket.error:
print ("Couldn't connect to the client")
s_TCP.close()
sys.exit()
Thanks in advance!!
The trivial answer is to set a shorter timeout and try to accept
several times. Because the socket is already listen
ing, no connection attempts will be lost “between” the calls to accept
. Remember to reset the timeout to whatever larger value after accepting a connection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.