TCP connection in python. Do you know how to print a timer whilst the socket is waiting to accept a connection request?

Viewed 117

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!!

1 Answers

The trivial answer is to set a shorter timeout and try to accept several times. Because the socket is already listening, no connection attempts will be lost “between” the calls to accept. Remember to reset the timeout to whatever larger value after accepting a connection.

Related