TCP-соединения не очищаются в Windows (python)Python

Программы на Python
Anonymous
TCP-соединения не очищаются в Windows (python)

Сообщение Anonymous »

Я использую сервер Windows на AWS, который передает некоторые данные устройствам IOT, но через некоторое время сервер перестает отвечать на запросы, потому что он зависает на вызове s.accept(), мне удалось определить это это происходит потому, что на сервере открыто слишком много TCP-соединений, поэтому ОС больше не выделяет ресурсы, что имеет смысл, но что для меня не имеет смысла, так это то, почему соединения открыты, но все еще открыты, потому что все они должны были быть закрыты. Вот пример моего кода, в котором в целях безопасности опущены части:

Код: Выделить всё

def connection(conn, addr):
conn.settimeout(10)
data = None
connection_time = datetime.now()
n_items = 0
try:
print(connection_time.strftime("[%d/%m/%Y, %H:%M:%S] "), "new connection started:", addr)
data = get_info(conn)
print(addr, data)

# serve client here, protocol omitted

except Exception as e:
print(f"{addr} connection error:" + str(e))
if data is not None:
add_connection_info(addr, data, connection_time)
try:
conn.close()
print(connection_time.strftime("[%d/%m/%Y, %H:%M:%S] "), "connection ended:", addr)
except Exception as e:
print(f"close failed: {addr} ; {e}")

if __name__ == '__main__':
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(cert, key, password=*omitted*)
s = socket.socket()
s = ssl_context.wrap_socket(s, server_side=True)
host = "0.0.0.0"
port = 12345  # not the actual port

print('Server started:', host, port)

s.bind((host, port))  # Bind to the port
s.listen()  # Now wait for client connection.
s.setblocking(False)
# Join completed threads and check connection status
threads = []
while True:
for thread in threads:
thread.join(0)
threads = [t for t in threads if t.is_alive()]
print(f"{len(threads)} active connections")
try:
# Use select to wait for a connection or timeout
rlist, _, _ = select.select([s], [], [], 100)  # 100 seconds timeout
if s in rlist:
s.settimeout(10)
# TODO timout here
c, addr = s.accept()
print(f"Accepted connection from {addr}")
thread = Thread(target=connection, args=(c, addr))
#thread.daemon = True
thread.start()
threads.append(thread)
print("thread started")
else:
print("No connection within 100 second period")

except BlockingIOError:
print("No connection ready")
except Exception as e:
print("error", str(e))

try:
c.close()
print(f"Connection from {addr} closed due to error.")
except Exception as e_close:
print(f"Failed to close connection after error: {str(e_close)}")
Я записываю выходные данные сервера, и когда я проверял последний раз после того, как увидел, что сервер зависает при каждой печати (connection_time.strftime("[%d/%m/%Y, % H:%M:%S] "), "начато новое соединение:", addr)
есть соответствующий print(connection_time.strftime("[%d/%m/%Y, % H:%M:%S] "), "соединение завершено:", addr) поэтому, насколько я могу судить, не должно быть открытых соединений, потому что print(f"{len(threads)} активные соединения") выводит, что активных потоков 0. Но когда я открываю монитор ресурсов Windows, есть более 50 открытых TCP с помощью Python даже для (ip, порт), которые должны были быть закрыты несколько часов назад и были зарегистрированы сервером как «завершенные», поэтому я не понимаю, почему они до сих пор .

Подробнее здесь: https://stackoverflow.com/questions/790 ... ows-python

Вернуться в «Python»