我有一个关于在同一事件循环上运行的两个异步服务器的问题。当我从客户端关闭一个连接时,我看到第二台服务器也停止了。
这是我的代码:
async def http_server(addr: str, port: int, verbose: int):
runner = aiohttp.AppRunner(await init_app())
await runner.setup()
site = web.TCPSite(runner, str(addr), port)
await site.start()
async def main(port: int, addr: str, verbose: int, restapiport: int):
# HTTP server
await http_server(str(addr), restapiport, verbose)
print(f'Serving RPC on {addr}:{restapiport} ...')
# TCP server for messaging
server = await asyncio.start_server(handle_client, str(addr), port)
addr = server.sockets[0].getsockname()
print(f'Serving MBE on {addr} CSID={os.environ["CSID"]}')
async with server:
await server.serve_forever()
当我从客户端关闭一个连接时,我得到以下异常(没关系):
Task exception was never retrieved
future: <Task finished coro=<handle_client() done, defined at /opt/xenv.py:19>
exception=ConnectionResetError(104, 'Connection reset by peer')>
Traceback (most recent call last):
File "/opt/xenv.py", line 41, in handle_client
data = await reader.readexactly(msg_headers.X_MSG_TCP_DATA_BUF_SIZE)
File "/usr/local/lib/python3.7/asyncio/streams.py", line 679, in readexactly
await self._wait_for_data('readexactly')
File "/usr/local/lib/python3.7/asyncio/streams.py", line 473, in _wait_for_data
await self._waiter
File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 814, in _
_read_ready__data_received
data = self._sock.recv(self.max_size)
ConnectionResetError: [Errno 104] Connection reset by peer
似乎 ConnectionResetError 异常会以某种方式影响其他异步任务。如何在不影响其他异步任务的情况下处理此异常?
这是异常之前的netstat:
root@5901ff922714:/opt# netstat
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 5901ff922714:34833 symulator_pm-b_1.:33330 ESTABLISHED
tcp 0 0 5901ff922714:34271 5901ff922714:25010 ESTABLISHED
tcp 0 0 5901ff922714:36695 5901ff922714:33330 ESTABLISHED
tcp 8192 0 5901ff922714:25010 5901ff922714:34271 ESTABLISHED
tcp 49152 0 5901ff922714:33330 5901ff922714:36695 ESTABLISHED
tcp 0 0 5901ff922714:40831 symulator_pm-b_1.:25011 ESTABLISHED
Active UNIX domain sockets (w/o servers)
Proto RefCnt Flags Type State I-Node Path
unix 3 [ ] STREAM CONNECTED 396830805
unix 3 [ ] STREAM CONNECTED 396830724
unix 3 [ ] STREAM CONNECTED 396830804
unix 3 [ ] STREAM CONNECTED 396830725
unix 2 [ ] DGRAM 396819365
这是异常后的netstat:
root@5901ff922714:/opt# netstat
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
Active UNIX domain sockets (w/o servers)
Proto RefCnt Flags Type State I-Node Path
unix 3 [ ] STREAM CONNECTED 396830805
unix 3 [ ] STREAM CONNECTED 396830724
unix 3 [ ] STREAM CONNECTED 396830804
unix 3 [ ] STREAM CONNECTED 396830725
任何帮助将非常感激