> On Oct 24, 2016, at 12:49 PM, Paul Sokolovsky <[email protected]> wrote:
> 
> .read() and .write() are generic methods of Python's stream interface
> ("protocol"). Sadly, Python's sockets don't implement stream interface
> natively, but require converting to a stream with .makefile() method.
> So, you can consider that in the example above,
> asyncio.open_connection() does the same as socket().makefile().
> Otherwise, it's the same as "sync ones". Except:
> 
>> writer.write(message.encode())
> 
> In asyncio, asynchronous library, .write() is somehow synchronous.
> 
>> data = yield from reader.read(100)
> 
> .read() is expectedly asynchronous.


First, both “read” and “write” ops are asynchronous in asyncio.  What you 
probably are trying to say is that “read” is a coroutine, whereas “write” is a 
regular method.  There is a good reason for that.

“read” is a coroutine because you have to wait until the data has arrived.  The 
arrival of the data is obvious, and you know with 100% certainty that you have 
the data.  So you can resume the coroutine one you have it.

“write” is a regular method because, contrary to “read”, you have no idea where 
the data that you have written is.  In curio, “socket.write” coroutine resumes 
when the corresponding system call succeeds, but it would be wrong to assume 
that the data you’re trying to send was received by anyone!  The only way of 
knowing that your “write" operation has really succeeded, is when you receive a 
confirmation from the client (how exactly that confirmation is carried is 
defined in the protocol you are implementing).

Network “write” is fundamentally different from file/memory “write".  asyncio 
handles read/write discrepancy in its streaming API, by letting users to write 
the data when they need, and the framework then takes care of the rest (and it 
will, in general, be more efficient this way).

When you work with the non-blocking low-level socket API in asyncio, you have 
‘loop.sock_sendall’ coroutine, that essentially does what you want - resumes 
after the write syscall.  It’s the correct API for low-level socket 
programming, but not for high-level protocol programming.

Yury

Reply via email to