Skip to content
Advertisement

Asyncio Streams automatically restarts to read data even after writer.close() is run

I followed the tutorial in https://docs.python.org/3/library/asyncio-stream.html to read data from a sensor (TCP protocol, PC as the server):

JavaScript

The program is supposed to finish after 1 second data transmission. However, the output is:

JavaScript

It repeated automatically and infinitely. What is the reason for this and How could I solve it?

Advertisement

Answer

Problem

serve_forever() listens to the port indefinitely. So, even though the individual connections close after 1 second, the server keeps accepting new connections. In this case, your sensor (client) seems to be creating a new connection after an old connection is closed, and since the server still accepts them, handle_server runs again from the top.

Solution

Maybe not the best way™, but one possible solution is to use a Future so that handle_server can signal the main code upon connection completion. The main code can then stop the server, avoiding new connections. This is how it can be done:

JavaScript

Couple of notes:

  • handle_server now takes one extra argument, first_connection_completion which is the future used to send signal from the function to the main code. The argument has been binded to the function using functools.partial. Within the function, set_result has been used to mark the future as completed.

  • serve_forever() is now wrapped by a create_task call. This is because we can’t await on it.

The new code looks messy, but you can always refactor. So a cleaner version would be:

JavaScript
Advertisement