client.py 1009 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import socket
  2. import sys
  3. # save values needed to talk to server
  4. saddr = sys.argv[1]
  5. uport = int(sys.argv[2])
  6. rcode = sys.argv[3]
  7. msg = sys.argv[4]
  8. # start udp socket
  9. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  10. # send msg to server to check rcode
  11. sock.sendto(rcode.encode(),(saddr, uport))
  12. # get reply from server, save the port, then check it
  13. confirmation, newaddr = sock.recvfrom(1024)
  14. rport = confirmation.decode()
  15. sock.sendto(rport.encode(), newaddr)
  16. confirm, neweraddr = sock.recvfrom(1024)
  17. if (confirm.decode() == "correct"):
  18. # got right port, close UDP connection
  19. sock.close
  20. # make TCP connection, send msg
  21. tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  22. tsock.connect((saddr, int(rport)))
  23. tsock.send(msg.encode())
  24. # get reply, print it, exit
  25. reply = tsock.recv(1024).decode()
  26. print("CLIENT_RCV_MSG='", reply, "'", sep="")
  27. tsock.close()
  28. sys.exit(0)
  29. else:
  30. print("Did not confirm the port, giving up.")
  31. sys.exit(1)