uvicorn 是如何监听 HTTP 请求的?

uvicorn/server.py

https://github.com/encode/uvicorn/blob/master/uvicorn/server.py

uvicorn 是如何监听 HTTP 请求的?

else:

# Standard case. Create a socket from a host/port pair.

try:

server = await loop.create_server(

create_protocol,

host=config.host,

port=config.port,

ssl=config.ssl,

backlog=config.backlog,

)

except OSError as exc:

logger.error(exc)

await self.lifespan.shutdown()

sys.exit(1)

assert server.sockets is not None

listeners = server.sockets

self.servers = [server]

if sockets is None:

self._log_started_message(listeners)

else:

# We're most likely running multiple workers, so a message has already been

# logged by `config.bind_socket()`.

pass

调用 server = await loop.create_server 创建了一个 server 时候,需要调用 server.serve_forever() 才能一直监听吧?

但是没有从 uvicorn 代码中看到有调用 serve_forever 的地方。那么 uvicorn 死循环监听 HTTP 的代码在哪里呢?


我为什么有这个疑问,是因为下面的 demo 代码,运行就退出了,不会一直死循环监听

import asyncio

from asyncio.base_events import Server

async def handle_client(reader, writer):

while True:

data = await reader.read(100)

if not data:

break

writer.write(data)

writer.close()

async def main():

loop = asyncio.get_running_loop()

server: Server = await loop.create_server(

handle_client, '127.0.0.1', 8888)

asyncio.run(main())

如果要一直监听,需要加 server.serve_forever()

import asyncio

from asyncio.base_events import Server

async def handle_client(reader, writer):

while True:

data = await reader.read(100)

if not data:

break

writer.write(data)

writer.close()

async def main():

loop = asyncio.get_running_loop()

server: Server = await loop.create_server(

handle_client, '127.0.0.1', 8888)

async with server:

await server.serve_forever()

asyncio.run(main())


回答:

它的代码中不就有loop = asyncio.get_running_loop()调用么?等于是用了asyncio的event loop事件,在event loop中监听端口的,而asyncio就提供了创建tcp server的方法: https://docs.python.org/3/library/asyncio-eventloop.html#asyn...

它那个create_server不就调用了这个方法?

以上是 uvicorn 是如何监听 HTTP 请求的? 的全部内容, 来源链接: utcz.com/p/938876.html

回到顶部