Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python asyncio http server

I try to build a base http server with the following code.

async def handle_client(client, address):
    print('connection start')
    data = await loop.sock_recv(client, 1024)
    resp = b'HTTP/1.1 404 NOT FOUND\r\n\r\n<h1>404 NOT FOUND</h1>'
    await loop.sock_sendall(client, resp)
    client.close()

async def run_server():
    while True:
        client, address = await loop.sock_accept(server)
        print('start')
        loop.create_task(handle_client(client,address))
        print(client)

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 3006))
server.listen(8)
print(1)
loop = asyncio.get_event_loop()
loop.run_until_complete(run_server())

The output I expect to get is

1
start
connection start

But the actual result of running is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1
start
start
start

It seems that the function in loop.create_task() is not being run, so now I got confuesed., what is the correct way to use loop.create_task()?

>Solution :

You need to await the task that is created via loop.create_task(), otherwise run_server() will schedule the task and then just exit before the result has been returned.

Try changing run_server() to the following:

async def run_server():
    while True:
        client, address = await loop.sock_accept(server)
        print('start')
        await loop.create_task(handle_client(client,address))
        print(client)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading