希望在一个时间范围内接受尽可能多的客户

Want to accept as many clients as possible in a time frame

我正在编写一个程序,允许 wifi 网络中的计算机连接到它,一段时间后它应该不再接受连接并准备好向所有连接的客户端发送消息

我试过 while 循环,但找不到限制时间的方法

这是我当前的代码: 导入套接字

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

您可以根据时间条件放置 while 循环,或者检查循环内的时间和超过时间的 break

while 基于时间条件的循环:

import datetime as dt

start = dt.datetime.utcnow()
while dt.datetime.utcnow() - start <= dt.timedelta(seconds=600):  # 600 secs = 10 mins
    # your code

while 循环中 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