xudp.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """
  2. python3 /home/server/repositories/repositories/sri-project.demo-py/3rdparty/xclient/xudp.py
  3. """
  4. import asyncio
  5. import struct
  6. class CustomProtocol:
  7. def __init__(self):
  8. self.data_received = asyncio.Future()
  9. def connection_made(self, transport):
  10. self.transport = transport
  11. def datagram_received(self, data, addr):
  12. self.data_received.set_result((data, addr))
  13. def connection_lost(self, exc):
  14. pass
  15. async def send_message(self, values, addr=('127.0.0.1', 20917)):
  16. data = struct.pack('!hh', *values)
  17. self.transport.sendto(data, addr)
  18. print(f"Sent values: {values}")
  19. response, _ = await self.data_received
  20. if response:
  21. received_values = struct.unpack('!hh', response)
  22. print(f"Received response: {received_values}")
  23. async def start_client(messages=[(100, 200)]):
  24. protocol = CustomProtocol()
  25. transport, _ = await asyncio.get_running_loop().create_datagram_endpoint(
  26. lambda: protocol,
  27. remote_addr=('127.0.0.1', 20917)
  28. )
  29. try:
  30. for values in messages:
  31. await protocol.send_message(values)
  32. finally:
  33. transport.close()
  34. if __name__ == "__main__":
  35. messages = [(100, 200), (300, 400), (500, 600)] # 示例消息列表
  36. asyncio.run(start_client(messages=messages))