1 客户端

  1. from socket import *
  2. from threading import Thread
  3. class UdpClient():
  4. def __init__(self, src_port, dst_host, dst_port):
  5. self.cli = socket(AF_INET, SOCK_DGRAM)
  6. self.cli.bind(('', src_port))
  7. self.dst_host = dst_host
  8. self.dst_port = dst_port
  9. def send(self, msg: str):
  10. self.cli.sendto(msg.encode(), (self.dst_host, self.dst_port))
  11. print('消息发送成功')
  12. def recv(self):
  13. try:
  14. data, addr = self.cli.recvfrom(1024)
  15. except:
  16. return
  17. response = data.decode()
  18. print('接收到来自{}的消息:{}'.format(addr, response))
  19. def t_read(cli: UdpClient):
  20. while True:
  21. print('正在等待消息...')
  22. cli.recv()
  23. def t_write(cli: UdpClient):
  24. while True:
  25. msg = input('输入要发的消息:')
  26. cli.send(msg)
  27. cli = UdpClient(8347, '192.168.3.67', 8367)
  28. t1 = Thread(target=t_read, args=(cli,))
  29. t2 = Thread(target=t_write, args=(cli,))
  30. t1.start()
  31. t2.start()
  32. t1.join()
  33. t2.join()

2 WireShark抓包

image.png