Reputation: 1342
This is probably a stupid question, but I'm missing something that I think is probably obvious:
I'm working with the Python 3.8 asyncio streams:
import asyncio
async def client_handler():
reader, writer = await asyncio.open_connection('127.0.0.1', 9128)
server_name = writer.get_extra_info('peername')[0]
print(f"Connecting to: { server_name }")
data = b''
close_client = False
try:
while not close_client:
print(data)
data = await reader.read(1024)
print(data)
if data != b'':
print(data.decode('utf-8'))
data = b''
writer.close()
except:
pass
finally:
writer.close()
await writer.wait_closed()
asyncio.run(client_handler())
I guess I expected that it would try to read 1024 bytes but if there was nothing there, then it would just return None or an empty byte string or something, but instead it just sits there until data is received.
Am I misunderstanding what read is supposed to do? Is there instead another method that I could use to peek into a buffer or poll to see if any data is actually incoming?
For instance, lets say I'm writing an example chat program server and client that need to be able to dynamically send and receive data at the same time... how do I implement that with the asyncio streams? Should I just build my own asyncio.Protocol subclass instead?
Upvotes: 0
Views: 1965
Reputation: 154866
You can use tools like asyncio.gather()
, asyncio.wait(return_when=FIRST_COMPLETED)
, and asyncio.wait_for()
to multiplex between different operations, such as reads from different streams, or reads and writes. Without additional details regarding your use case it's hard to give you concrete advice how to proceed.
Building an asyncio.Protocol
or using feed_eof()
directly is almost certainly the wrong approach, unless you are writing very specialized software and know exactly what you are doing.
Upvotes: 2