Search code examples
python-3.xtornadotcpserver

Tornado read until close method error


I am trying to create TCP server in python with a tornado. My handle stream method looks like this,

async def handle_stream(self, stream, address):
    while True:
        try:
            stream.read_until_close(streaming_callback=self._on_read)
        except StreamClosedError:
            break

in the _on_read method, I am trying to read and process the data but whenever a new client connects to the server it gives AssertionError: Already reading error.

 File "/.local/lib/python3.5/site-packages/tornado/iostream.py", line 525, in read_until_close
    future = self._set_read_callback(callback)
  File "/.local/lib/python3.5/site-packages/tornado/iostream.py", line 860, in _set_read_callback
    assert self._read_future is None, "Already reading"

Solution

  • read_until_close asynchronously reads all data from the socket until it is closed. read_until_close has to be called once but the cycle forces the second call that's why you got an error:

    • on the first iteration, read_until_close sets streaming_callback and returns Future so that you could await it or use later;
    • on the second iteration, read_until_close raises an exception since you already set a callback on the first iteration.

    read_until_close returns Future object and you can await it to make things work:

    async def handle_stream(self, stream, address):
        try:
            await stream.read_until_close(streaming_callback=self._on_read)
        except StreamClosedError:
            # do something