简体   繁体   English

Python 异步 http 服务器

[英]Python asyncio http server

I try to build a base http server with the following code.我尝试使用以下代码构建基础 http 服务器。

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我期望得到的 output 是

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()? loop.create_task() 中的 function 似乎没有运行,所以现在我很困惑。使用 loop.create_task() 的正确方法是什么?

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.您需要等待通过loop.create_task()创建的任务,否则run_server()将安排任务,然后在返回结果之前退出。

Try changing run_server() to the following:尝试将run_server()更改为以下内容:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM