dabeaz / curio

Good Curio!
Other
4.04k stars 243 forks source link

When do I need to use `as_stream()`? #207

Closed SuperShinyEyes closed 7 years ago

SuperShinyEyes commented 7 years ago

This is a question not an issue report.

I was following an echo server tutorial.

from curio import run, spawn, tcp_server

async def echo_client(client, addr):
    print('Connection from', addr)
    while True:
        data = await client.recv(1000)
        if not data:
            break
        await client.sendall(data)
    print('Connection closed')

if __name__ == '__main__':
    run(tcp_server, '', 25000, echo_client)

The same code in stream mode

from curio import run, spawn, tcp_server

async def echo_client(client, addr):
    print('Connection from', addr)
    s = client.as_stream()
    while True:
        data = await s.read(1000)
        if not data:
            break
        await s.write(data)
    print('Connection closed')

if __name__ == '__main__':
    run(tcp_server, '', 25000, echo_client)

In How-to, it says

If you want to a use a file-like streams interface, use the as_stream() method

But I don't see any clear reason/use-case/advantage of this stream mode. When should I use it? Thanks.

jkbbwr commented 7 years ago

One of the main reasons is it makes a socket behave more like a file. You can for example iterate directly over the socket in stream mode.

async for line in s:
    print(line)
SuperShinyEyes commented 7 years ago

Thanks @jkbbwr. I got it.