Graceful interrupt of EventLoop.sock_accept()
<p>Consider the following code, how to stop execution in <code>listen()</code>? it seems to hang after <code>sock.close()</code> being called. No exceptions are raised</p>

<pre><code>#!/usr/bin/env python3.5

import asyncio, socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 8080))
sock.listen()
sock.setblocking(0)

async def listen():
    print('listen')
    try:
        while True:
            await asyncio.get_event_loop().sock_accept(sock)
            print('accepted')
    except:
        print('exc')

async def stop():
    await asyncio.sleep(1)
    sock.close()
    print('stopped')


asyncio.ensure_future(listen())
asyncio.ensure_future(stop())
asyncio.get_event_loop().run_forever()
</code></pre>

<p>Closing the socket or removing the file descriptor using <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.remove_reader" rel="nofollow">loop.remove_reader</a> does not notify <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.sock_accept" rel="nofollow">loop.sock_accept</a>.</p>

<p>Either cancel it explicitly:</p>

<pre><code># Listening
accept_future = asyncio.ensure_future(loop.sock_accept(sock))
await accept_future
[...]
# Closing
loop.remove_reader(sock.fileno())
sock.close()
accept_future.cancel()
</code></pre>

<p>or use higher-level coroutines such as <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.create_server" rel="nofollow">loop.create_server</a> or <a href="https://docs.python.org/3/library/asyncio-stream.html#asyncio.start_server" rel="nofollow">asyncio.start_server</a>:</p>

<pre><code># Using a protocol factory
server = await loop.create_server(protocol_factory, sock=sock) 
# Using callback and streams
server = await asyncio.start_server(callback, sock=sock)
</code></pre>

python sockets python-asyncio