我想设置一个时间来接受来自套接字的连接。
当我使用s.accept()
时,它将等待直到建立连接。我希望服务器在有限的时间内接受连接,然后执行该过程,然后再次接受连接。
Pseduo代码
Accept connection for 0.1 sec
Procedure()
Accept connection for 0.1 sec
Procedure()
.
.
.
我在Windows 10上使用python 3.7.0。
答案 0 :(得分:1)
对socket
库中example的非常简单的修改:
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
TIMEOUT = 0.1
while True:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
s.settimeout(TIMEOUT)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
data = conn.recv(1024)
if data:
whatever_procedure(data)
except socket.timeout:
print(f'Timeout occurred after {TIMEOUT}')
your_procedure_in_case_timeout()