Handling of disconnecting clients in asyncio
Johannes Bauer
dfnsonfsduifb at gmx.de
Tue Sep 24 05:50:49 EDT 2019
Hi group,
I'm trying to get into async programming using Python. Concretely I open
a UNIX socket server in my application. The UNIX socket server generates
events and also receives commands/responds to them.
I do this by:
async def _create_local_server(self):
await asyncio.start_unix_server(self._local_server_tasks, path = "foo"))
And then gather the command/response and event tasks:
async def _local_server_tasks(self, reader, writer):
await asyncio.gather(
self._local_server_commands(reader, writer),
self._local_server_events(reader, writer),
)
I believe so far this is okay, right? If not, please tell me. Anyways,
the event loop as an example:
async def _local_server_events(self, reader, writer):
while True:
await asyncio.sleep(1)
writer.write(b"event\n")
And the command/response loop, obviously simplified:
async def _local_server_commands(self, reader, writer):
while True:
msg = await reader.readline()
writer.write(msg)
Now I'm having the following issue: A client connects to my server and
then properly disconnects (shutdown/RDWR, close). This causes the await
reader.readline() to return an empty message (after which I can properly
end the _local_server_commands loop).
However, the _local_server_events loop does get no such notificiation.
Nor does writer.write() throw an exception that I could catch (and exit
as a consequence). Instead, I get this on stderr:
socket.send() raised exception.
socket.send() raised exception.
socket.send() raised exception.
socket.send() raised exception.
[...]
My questions are:
1. Is the design generally sane or is this usually done differently?
I.e., am I making any obvious beginner mistakes?
2. What is the proper way of discovering a peer has disconnected and
exiting cleanly?
Thanks in advance,
All the best,
Johannes
--
"Performance ist nicht das Problem, es läuft ja nachher beides auf der
selben Hardware." -- Hans-Peter Diettrich in d.s.e.
More information about the Python-list
mailing list