python3.7的asyncio的socket server

Posted 70 months ago python asyncio socket linux

猝不及防的看了一下文档 发现出现这个简单实用的语法糖?


import asyncio

async def client_connected(reader:asyncio.StreamReader, writer: asyncio.StreamWriter):
    e=await reader.read(10*1024*1024)
    print(e)
    writer.write(b"200 hello world")
    await writer.drain()
    writer.close()

async def main(host, port):
    srv = await asyncio.start_server(
        client_connected, host, port)
    await srv.serve_forever()

if __name__ == "__main__":
    asyncio.run(main('127.0.0.1', 8080))

点击评论