I am writing a program that allows computers within a wifi network to connect to it, after a certain period of time it should no longer accept connections and be ready to send a message to all connected clients
I have tried a while loop but I can't find a way to time limit it
here is my current code: import socket
connections = []
s = socket.socket()
host = socket.gethostname()
port = 8080
s.bind((host, port))
s.listen(1)
print(".....")
while True:
conn, addr = s.accept()
connections.append([conn, addr])
connections[-1][0].send("welcome".encode())
#after a certain amount of time I want that loop to stop and wait for a
command to be typed or some other input method
You can either put the while
loop based on a time condition or check the time within the loop and break
when the time is exceeded.
while
loop based on a time condition:
import datetime as dt
start = dt.datetime.utcnow()
while dt.datetime.utcnow() - start <= dt.timedelta(seconds=600): # 600 secs = 10 mins
# your code
Within the while
loop with a break
:
start = dt.datetime.utcnow()
while True:
if dt.datetime.utcnow() - start > dt.timedelta(seconds=600):
break # end the loop after 10 mins
# your code