I'm trying to experiment a bit with python asyncio to improve in that area, for self teaching purposes I'm trying to connect to redis, send some commands and read the response, this can fall under generic "read a stream of data from some source". The problem I cannot solve is how to read data in chunks, since the connection is not being closed between server and client and the termination sequence \r\n
could be met more than once. If I await when there is no more data of course the call will block until something else will be received.
class Client:
def __init__(self, loop, host='127.0.0.1', port=6379):
self.host = host
self.port = port
self.reader = None
self.writer = None
self.loop = loop
@asyncio.coroutine
def _connect(self):
self.reader, self.writer = yield from asyncio.open_connection(
self.host, self.port, loop=self.loop)
async def read(self, b=4096):
resp = b''
while True:
chunk = await self.reader.read(b)
if chunk:
resp += chunk
else:
break
return resp
Let's pretend I want to read the response in chunks of 2 bytes (yes is stupid but it's just for this learning purpose) so:
loop = asyncio.get_event_loop()
client = Client(loop)
..... sends some commands here ....
resp = await client.read(2)
I cannot figure out how while not knowing the length of the server response the code can still be safe when the response is longer than the bytes read from the socket.