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
The stream objects are higher level and provide many useful methods:
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:
reader.feed_data
is called.feed_data
triggers another callback that restores the execution of reader.read()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With