{"id":2827,"date":"2025-03-16T12:17:48","date_gmt":"2025-03-16T04:17:48","guid":{"rendered":"https:\/\/www.laixuexila.com\/?p=2827"},"modified":"2025-03-16T12:17:48","modified_gmt":"2025-03-16T04:17:48","slug":"python3-%e7%bd%91%e7%bb%9c%e7%bc%96%e7%a8%8b6%ef%bc%9a%e5%bc%82%e6%ad%a5%e7%bd%91%e7%bb%9c%e7%bc%96%e7%a8%8b-asyncio","status":"publish","type":"post","link":"https:\/\/www.laixuexila.com\/index.php\/2025\/03\/16\/python3-%e7%bd%91%e7%bb%9c%e7%bc%96%e7%a8%8b6%ef%bc%9a%e5%bc%82%e6%ad%a5%e7%bd%91%e7%bb%9c%e7%bc%96%e7%a8%8b-asyncio\/","title":{"rendered":"Python3 \u7f51\u7edc\u7f16\u7a0b6\uff1a\u5f02\u6b65\u7f51\u7edc\u7f16\u7a0b (asyncio)"},"content":{"rendered":"\n<p>\u5728\u9ad8\u5e76\u53d1\u7f51\u7edc\u5e94\u7528\u4e2d\uff0c\u4f20\u7edf\u7684 <code>socket<\/code> \u548c <code>socketserver<\/code> \u53ef\u80fd\u4f1a\u9047\u5230 <strong>\u963b\u585e<\/strong> \u95ee\u9898\u3002Python \u7684 <code>asyncio<\/code> \u63d0\u4f9b\u4e86\u4e00\u79cd <strong>\u5f02\u6b65 IO<\/strong> \u673a\u5236\uff0c\u53ef\u4ee5\u5b9e\u73b0\u9ad8\u6548\u7684\u7f51\u7edc\u7f16\u7a0b\u3002<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>6.1 <code>asyncio<\/code> \u57fa\u7840<\/strong><\/h2>\n\n\n\n<p><code>asyncio<\/code> \u5141\u8bb8\u4f7f\u7528 <code>async<\/code> \u548c <code>await<\/code> \u5173\u952e\u5b57\u7f16\u5199 <strong>\u975e\u963b\u585e<\/strong> \u4ee3\u7801\u3002<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6.1.1 \u521b\u5efa\u5f02\u6b65\u4efb\u52a1<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio\n\nasync def my_task():\n    print(\"\u4efb\u52a1\u5f00\u59cb...\")\n    await asyncio.sleep(2)  # \u6a21\u62df IO \u64cd\u4f5c\n    print(\"\u4efb\u52a1\u5b8c\u6210\uff01\")\n\nasyncio.run(my_task())<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6.1.2 \u5e76\u53d1\u6267\u884c\u591a\u4e2a\u4efb\u52a1<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio\n\nasync def task(name, seconds):\n    print(f\"{name} \u5f00\u59cb...\")\n    await asyncio.sleep(seconds)\n    print(f\"{name} \u5b8c\u6210\uff01\")\n\nasync def main():\n    await asyncio.gather(task(\"\u4efb\u52a1 1\", 2), task(\"\u4efb\u52a1 2\", 3), task(\"\u4efb\u52a1 3\", 1))\n\nasyncio.run(main())<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>6.2 \u5f02\u6b65 TCP \u670d\u52a1\u5668<\/strong><\/h2>\n\n\n\n<p>\u4f7f\u7528 <code>asyncio<\/code> \u53ef\u4ee5\u521b\u5efa <strong>\u5f02\u6b65 TCP \u670d\u52a1\u5668<\/strong>\uff0c\u652f\u6301\u9ad8\u5e76\u53d1\u8fde\u63a5\u3002<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6.2.1 \u5f02\u6b65 TCP \u670d\u52a1\u5668<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio\n\nasync def handle_client(reader, writer):\n    data = await reader.read(100)  # \u8bfb\u53d6\u6570\u636e\n    message = data.decode()\n    addr = writer.get_extra_info(\"peername\")\n    print(f\"\u6536\u5230\u6765\u81ea {addr} \u7684\u6570\u636e: {message}\")\n\n    writer.write(b\"Hello from Async TCP Server\")\n    await writer.drain()  # \u53d1\u9001\u6570\u636e\n    writer.close()\n\nasync def main():\n    server = await asyncio.start_server(handle_client, \"0.0.0.0\", 8888)\n    print(\"\u5f02\u6b65 TCP \u670d\u52a1\u5668\u8fd0\u884c\u5728\u7aef\u53e3 8888...\")\n    async with server:\n        await server.serve_forever()\n\nasyncio.run(main())<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6.2.2 \u5f02\u6b65 TCP \u5ba2\u6237\u7aef<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio\n\nasync def tcp_client():\n    reader, writer = await asyncio.open_connection(\"127.0.0.1\", 8888)\n    writer.write(b\"Hello Async Server\")\n    await writer.drain()\n\n    response = await reader.read(100)\n    print(f\"\u6536\u5230\u670d\u52a1\u5668\u54cd\u5e94: {response.decode()}\")\n\n    writer.close()\n    await writer.wait_closed()\n\nasyncio.run(tcp_client())<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>6.3 \u5f02\u6b65 UDP \u670d\u52a1\u5668<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6.3.1 \u5f02\u6b65 UDP \u670d\u52a1\u5668<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio\n\nclass MyUDPServerProtocol(asyncio.DatagramProtocol):\n    def datagram_received(self, data, addr):\n        print(f\"\u6536\u5230\u6765\u81ea {addr} \u7684\u6570\u636e: {data.decode()}\")\n        self.transport.sendto(b\"Hello from Async UDP Server\", addr)\n\nasync def main():\n    loop = asyncio.get_running_loop()\n    transport, protocol = await loop.create_datagram_endpoint(\n        lambda: MyUDPServerProtocol(), local_addr=(\"0.0.0.0\", 9999)\n    )\n    print(\"\u5f02\u6b65 UDP \u670d\u52a1\u5668\u8fd0\u884c\u5728\u7aef\u53e3 9999...\")\n    await asyncio.sleep(3600)  # \u8fd0\u884c 1 \u5c0f\u65f6\n\nasyncio.run(main())<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6.3.2 \u5f02\u6b65 UDP \u5ba2\u6237\u7aef<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio\n\nasync def udp_client():\n    loop = asyncio.get_running_loop()\n    transport, protocol = await loop.create_datagram_endpoint(\n        lambda: asyncio.DatagramProtocol(), remote_addr=(\"127.0.0.1\", 9999)\n    )\n\n    transport.sendto(b\"Hello Async UDP Server\")\n    await asyncio.sleep(1)  # \u7b49\u5f85\u670d\u52a1\u5668\u54cd\u5e94\n\nasyncio.run(udp_client())<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>6.4 <code>aiohttp<\/code>\uff1a\u5f02\u6b65 HTTP \u5ba2\u6237\u7aef\u4e0e\u670d\u52a1\u5668<\/strong><\/h2>\n\n\n\n<p><code>aiohttp<\/code> \u662f\u4e00\u4e2a <strong>\u5f02\u6b65 HTTP \u5e93<\/strong>\uff0c\u9002\u7528\u4e8e\u722c\u866b\u3001API \u8c03\u7528\u548c Web \u670d\u52a1\u5668\u3002<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6.4.1 \u5b89\u88c5 <code>aiohttp<\/code><\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>pip install aiohttp<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6.4.2 \u521b\u5efa\u5f02\u6b65 HTTP \u670d\u52a1\u5668<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>from aiohttp import web\n\nasync def handle(request):\n    return web.Response(text=\"Hello, Async HTTP Server!\")\n\napp = web.Application()\napp.router.add_get(\"\/\", handle)\n\nweb.run_app(app, host=\"0.0.0.0\", port=8080)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6.4.3 \u521b\u5efa\u5f02\u6b65 HTTP \u5ba2\u6237\u7aef<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import aiohttp\nimport asyncio\n\nasync def fetch():\n    async with aiohttp.ClientSession() as session:\n        async with session.get(\"http:\/\/127.0.0.1:8080\") as response:\n            print(await response.text())\n\nasyncio.run(fetch())<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>\u4e0b\u7bc7\u6587\u7ae0\u6211\u4eec\u5c06\u4ecb\u7ecd WebSocket \u7f16\u7a0b\uff0c\u5b9e\u73b0\u5b9e\u65f6\u53cc\u5411\u901a\u4fe1\uff01<\/strong> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5728\u9ad8\u5e76\u53d1\u7f51\u7edc\u5e94\u7528\u4e2d\uff0c\u4f20\u7edf\u7684 socket \u548c socketserver \u53ef\u80fd\u4f1a\u9047\u5230 \u963b\u585e \u95ee\u9898\u3002Python  [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":2828,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[79],"tags":[],"class_list":["post-2827","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-3-"],"_links":{"self":[{"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/posts\/2827","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/comments?post=2827"}],"version-history":[{"count":1,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/posts\/2827\/revisions"}],"predecessor-version":[{"id":2829,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/posts\/2827\/revisions\/2829"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/media\/2828"}],"wp:attachment":[{"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/media?parent=2827"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/categories?post=2827"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.laixuexila.com\/index.php\/wp-json\/wp\/v2\/tags?post=2827"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}