Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use protocol or streams in asyncio?

I'm very new to asyncio and was wondering which API is better than the other in terms of better practice, protocol or streams?

To me, protocol(callback based API) seems easier to work with since there are already connection_made and data_received methods provided to you. With streams(coroutine based API) you have to manage connections and read data yourself, but I feel like it utilizes concept of coroutine more, which seems a good thing to me.

this is how i listen to incoming data, feels awkward to me. I can also use readeexactly but sometimes it raises IncompleteReadError.

message_body = b''
message_length = SOME_NUMBER
while True:
    while len(message_body) < message_length:
        try:
            message_body_chunk = await reader.read(message_length - len(message_body))
        except Exception as e:
            self.logger.error(e)
            return
            if not message_body_chunk:
                return
            message_body += message_body_chunk
like image 551
shangsunset Avatar asked Jul 05 '16 21:07

shangsunset


1 Answers

The stream objects are higher level and provide many useful methods:

  • Several ways to read data: reader.read, readline, readuntil, readexactly
  • Check if EOF has been reached: reader.ateof
  • Control write flow: writer.drain

Like any abstraction, this comes at a cost: coroutine are a bit less reactive than callbacks. For instance reader.read() involves at least two event loop callbacks:

  • When some data is received, a callback is triggered and reader.feed_data is called.
  • Then feed_data triggers another callback that restores the execution of reader.read().
like image 175
Vincent Avatar answered Nov 17 '22 20:11

Vincent