Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 471
Krupa Suthar Avatar asked Feb 23 '26 07:02

Krupa Suthar


1 Answers

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
like image 127
Gennady Kandaurov Avatar answered Feb 24 '26 22:02

Gennady Kandaurov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!