1

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()
  • This is all my server code. I can open two connections to it so I know it's being threaded by asyncio. – Jacob Chrzanowski May 22 '18 at 18:30
  • asyncio doesn't spawn multiple threads (unless you tell it to), it's completely single-threaded. It does its magic using coroutines, a form of cooperative multi-tasking. How exactly are you trying to "kill" the code? – user4815162342 May 22 '18 at 18:39
  • Ctrl-C, so through a SIGINT. I'm on Windows 10 Ver. 1709 Build 16299.125 if that makes any difference. Are you saying I should make a new coroutine that listens for a SIGINT using the signal library? – Jacob Chrzanowski May 22 '18 at 18:43
  • No, I just misunderstood what you meant by "killing" the code. – user4815162342 May 22 '18 at 19:03
  • In Windows system, CTRL+C interrupt is only sent to the affected program **after** it has processed data (such as from coroutines or transport). This is a Python bug on signal handling in Windows system. – yoonghm Sep 14 '18 at 23:31

0 Answers0