""" python3 /home/server/repositories/repositories/sri-project.demo-py/3rdparty/xclient/xudp.py """ import asyncio import struct class CustomProtocol: def __init__(self): self.data_received = asyncio.Future() def connection_made(self, transport): self.transport = transport def datagram_received(self, data, addr): self.data_received.set_result((data, addr)) def connection_lost(self, exc): pass async def send_message(self, values, addr=('127.0.0.1', 20917)): data = struct.pack('!hh', *values) self.transport.sendto(data, addr) print(f"Sent values: {values}") response, _ = await self.data_received if response: received_values = struct.unpack('!hh', response) print(f"Received response: {received_values}") async def start_client(messages=[(100, 200)]): protocol = CustomProtocol() transport, _ = await asyncio.get_running_loop().create_datagram_endpoint( lambda: protocol, remote_addr=('127.0.0.1', 20917) ) try: for values in messages: await protocol.send_message(values) finally: transport.close() if __name__ == "__main__": messages = [(100, 200), (300, 400), (500, 600)] # 示例消息列表 asyncio.run(start_client(messages=messages))