昨天在招聘网里,搜关于python就业职位,其中有一条招聘信息要求会掌握几个异步socket框架:
然后想了想既然学了socket,和异步,掌握一个异步sokcet库应该没什么问题吧。
asyncio:一个用来写并发编程的库
========================================================官方文档=====================================================================
https://docs.python.org/zh-cn/3/library/asyncio.html
asyncio 是用来编写 并发 代码的库,使用 async/await 语法。
asyncio 被用作多个提供高性能 Python 异步框架的基础,包括网络和网站服务,数据库连接库,分布式任务队列等等。
asyncio 往往是构建 IO 密集型和高层级 结构化 网络代码的最佳选择。
asyncio 提供一组 高层级 API 用于:
-
并发地 运行 Python 协程 并对其执行过程实现完全控制;
-
执行 网络 IO 和 IPC;
-
控制 子进程;
-
通过 队列 实现分布式任务;
-
同步 并发代码;
此外,还有一些 低层级 API 以支持 库和框架的开发者 实现:
-
使用 transports 实现高效率协议;
-
通过 async/await 语法 桥接 基于回调的库和代码。
========================================================官方文档=====================================================================
import asyncio
async def myfun(i):
print('start {}th'.format(i))
await asyncio.sleep(1) # 休眠,模拟IO
print('finish {}th'.format(i))
loop = asyncio.get_event_loop() # 获取当前循环
myfun_list = (myfun(i) for i in range(10))
loop.run_forever
loop.run_until_complete(asyncio.gather(*myfun_list))
简单使用asynico模拟异步
import asyncio
async def tcp_echo_client(message):
reader, writer = await asyncio.open_connection(
'127.0.0.1', 8888)
print(f'Send: {message!r}')
writer.write(message.encode())
data = await reader.read(100)
print(f'Received: {data.decode()!r}')
print('Close the connection')
writer.close()
asyncio.run(tcp_echo_client('Hello World!'))
SOCKET_client.py
import asyncio
async def handle_echo(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
print(f"Send: {message!r}")
writer.write(data)
await writer.drain()
print("Close the connection")
writer.close()
async def main():
server = await asyncio.start_server(
handle_echo, '127.0.0.1', 8888)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
async with server:
await server.serve_forever()
asyncio.run(main())
SOCKET_server.py
成功实现异步通信!