I have a problem with blocking ports in python 3.6.5 using Asyncio . The code below accepts TCP connections and multi-threads itself. My issue is I can't kill it unless there is an active TCP connection, otherwise it stays unresponsive. There is a section below that is supposed to handle that but it doesn't work unless there is an open TCP connection.
Can anyone help me understand what is happening and how to fix it?
import asyncio
async def handle_echo(reader, writer):
data = await reader.read(100)
message = data.decode()
while(message != "-"):
addr = writer.get_extra_info('peername')
print("Received %r from %r" % (message, addr))
print("Send: %r" % message)
writer.write(data)
await writer.drain()
data = await reader.read(100)
message = data.decode()
print("Close the client socket")
writer.close()
loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
server = loop.run_until_complete(coro)
# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()