dimanche 26 juillet 2020

Socket listen for random time, then stop listening and continue other code

My end goal is to have a program start-up, and then stay in a 'listening for connections' mode for a random amount of time (between 0 and 10 seconds) and then continue on to a different block of code.

This is what I have so far, but the time.sleep would mean that it is going to block the code from accepting connections. Not what I want. I want it alive and able to connect throughout the random amount of time.

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sReceive:

                sReceive.bind(('0.0.0.0', port))
                sReceive.listen()
                print('Listening on ', port)

                time.sleep(random.uniform(0.0, 10.0))
                #Here, after the random time has elapsed, the socket should close and jump to "otherCode()" if
#no connection has been received in that time.
                conn, addr = sReceive.accept()

otherCode()

Is there something with time.perf_counter that I am missing? Or do I just need a new thread?

Thank you!




Aucun commentaire:

Enregistrer un commentaire