Я сделал этот очень простой пример сервера:
Код: Выделить всё
import asyncio
async def handle_client(reader, writer):
address = writer.get_extra_info('peername')
print(f"Connection: {address}")
try:
while True:
data = await reader.read(1024)
if not data:
print(f"Disconnected: {address}.")
break
print(f"{address} Send: {data.decode()}")
writer.write('👍\n'.encode())
await writer.drain()
except Exception as e:
print(f"Something bad happened: {e}")
finally:
print(f"Closed: {address}")
writer.close()
await writer.wait_closed()
async def main():
server = await asyncio.start_server(handle_client, '0.0.0.0', 5678)
async with server:
await server.serve_forever()
asyncio.run(main())
В настоящее время моим лучшим подходом было использование таймаута для принудительного отключения, как в этом примере:
р>
Код: Выделить всё
import asyncio
async def handle_client(reader, writer):
address = writer.get_extra_info('peername')
print(f"Connection: {address}")
try:
while True:
data = await asyncio.wait_for(reader.read(1024), timeout=10.0)
if not data:
print(f"Disconnected: {address}.")
break
print(f"{address} Send: {data.decode()}")
writer.write('👍\n'.encode())
await writer.drain()
except asyncio.TimeoutError:
print(f"Timeout: {address}")
except Exception as e:
print(f"Something bad happened: {e}")
finally:
print(f"Closed: {address}")
writer.close()
await writer.wait_closed()
async def main():
server = await asyncio.start_server(handle_client, '0.0.0.0', 5678)
async with server:
await server.serve_forever()
asyncio.run(main())
Есть ли лучший способ узнать, когда произошло отключение, без необходимости ждать несколько минут тайм-аута?Спасибо за внимание.
Подробнее здесь: https://stackoverflow.com/questions/787 ... connection