xtcp.py 964 B

12345678910111213141516171819202122232425262728293031
  1. """
  2. python3 /home/server/repositories/repositories/sri-project.demo-py/3rdparty/xclient/xtcp.py
  3. """
  4. import asyncio
  5. import struct
  6. async def send_message(reader, writer, values):
  7. data = struct.pack('!hh', *values)
  8. writer.write(data)
  9. await writer.drain()
  10. print(f"Sent values: {values}")
  11. size = struct.calcsize('!hh')
  12. response = await reader.read(size)
  13. if response:
  14. received_values = struct.unpack('!hh', response)
  15. print(f"Received response: {received_values}")
  16. async def start_client(host='127.0.0.1', port=20917, messages=[(100, 200)]):
  17. reader, writer = await asyncio.open_connection(host, port)
  18. try:
  19. for values in messages:
  20. await send_message(reader, writer, values)
  21. finally:
  22. writer.close()
  23. await writer.wait_closed()
  24. if __name__ == "__main__":
  25. messages = [(100, 200), (300, 400), (500, 600)] # 示例消息列表
  26. asyncio.run(start_client(messages=messages))