0

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
Avi Baruch
  • 112
  • 2
  • 8

1 Answers1

1

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
aneroid
  • 12,983
  • 3
  • 36
  • 66
  • I have thought about this method but s.accept stops the loop until it receives a connection meaning only if a connection is bridged will it look to see if the time is up. I need some counter externally to break the loop if possible. Thanks for the answer though – Avi Baruch Jan 07 '19 at 14:36