Issue
Consider the following code, how to stop execution in listen()
? it seems to hang after sock.close()
being called. No exceptions are raised
#!/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()
Solution
Closing the socket or removing the file descriptor using loop.remove_reader does not notify loop.sock_accept.
Either cancel it explicitly:
# Listening
accept_future = asyncio.ensure_future(loop.sock_accept(sock))
await accept_future
[...]
# Closing
loop.remove_reader(sock.fileno())
sock.close()
accept_future.cancel()
or use higher-level coroutines such as loop.create_server or asyncio.start_server:
# 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)
Answered By - Vincent
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.