python3异步数据报库
jetblack-datagram的Python项目详细描述
jetblack数据报
用于UDP数据报客户端和服务器的Python3.8+asyncio帮助程序库。在
状态
这是可行的,但仍在持续发展中,因此可能会有突破性的变化。在
概述
这个包为UDP数据报提供了一个简单的asyncioapi,下面是 类似于TCP流API的模式。在
UDP服务器是通过调用start_udp_server
来启动的,它是
类似于
start_server
由asyncio
提供的函数。
这将返回一个DatagramServer
,它提供读取(read
)、写入(sendto
)的方法,
并关闭(close
和wait_closed
)。这与提供
当客户端与读写流连接时的回调。这是因为UDP是无连接的
所以没有连接(或断开)事件。数据也以包的形式发送和接收,
因此,对于eb来说,提供单独的读写流似乎没有好处。在
下面创建一个服务器,读取然后写入一些数据。在
server=awaitstart_udp_server(('0.0.0.0',8000))data,addr=awaitserver.recvfrom()print(f"Received {data} from {addr}")server.sendto(b"Hello",addr)server.close()awaitserver.wait_closed()
UDP客户端是通过调用open_udp_connection
来启动的,这与
致
open_connection
函数由asyncio
库为TCP提供,它返回一个DatagramClient
。这提供了与
服务器,但是addr
在读或写时不存在,因为套接字是绑定的
创建时的服务器地址。在
安装
使用pip安装。在
pip install jetblack-datagram
入门
要创建echo服务器:
importasynciofromjetblack_datagramimportstart_udp_serverasyncdefmain():server=awaitstart_udp_server(('127.0.0.1',9999))count=0whilecount<5:count+=1print("Reading")data,addr=awaitserver.recvfrom()print(f"Received {data!r} from {addr}")print(f"Send {data!r} to {addr}")server.sendto(data,addr)print("Closing")server.close()print("Waiting for server to close")awaitserver.wait_closed()print("Closed")print("Done")if__name__=='__main__':asyncio.run(main())
要创建echo客户端:
importasynciofromjetblack_datagramimportopen_udp_connectionasyncdefmain():client=awaitopen_udp_connection(('127.0.0.1',9999))print("Sending data")client.send(b"Hello, World!")print("reading data")data=awaitclient.recv()print(f"Received {data!r}")print("closing client")client.close()print("waiting for client to close")awaitclient.wait_closed()if__name__=='__main__':asyncio.run(main())
使用
UDP协议是无连接的,因此与TCP不同 没有必要为每个服务器连接提供读取器,或者 为连接提供回调。在
普通
以下方法对客户机和服务器都很常见。在
- close()->无
- 异步等待已关闭()->;无
服务器
以下方法特定于服务器。在
- 发送到(data:bytes,addr:Union[Address,str])—>;无
- async recvfrom()->;元组[字节,地址]
客户
以下方法是特定于客户端的。在
- 发送(数据:字节)->无
- async recv()-字节
助手
有一个助手来创建服务器和客户端。在
对于服务器:
asyncdefstart_udp_server(addr:Address,*,loop:Optional[AbstractEventLoop]=None,maxreadqueue:int=0)->DatagramServer:
对于客户:
asyncdefopen_udp_connection(addr:Address,*,loop:Optional[AbstractEventLoop]=None,maxreadqueue:int=0)->DatagramClient:
- 项目
标签: