Home > Software design >  Python asyncio http server
Python asyncio http server

Time:01-27

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

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()?

CodePudding user response:

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)
  •  Tags:  
  • Related