Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. #Client
  2. import socket
  3. import struct
  4. import random
  5.  
  6. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  7. s.connect((socket.gethostname(), 1032))
  8.  
  9. guess = 0
  10.  
  11. while guess == 0:
  12. n = random.randint(0, 10)
  13. print(f"The client's number{n}")
  14.  
  15. s.send(struct.pack("!H", n))
  16.  
  17. nr = s.recv(2)
  18. guess = struct.unpack("!H", nr)[0]
  19. print(f"Guess: {guess}")
  20.  
  21. nr = s.recv(2)
  22. nr = struct.unpack("!H", nr)
  23. fullMsg = ""
  24. for i in range(nr):
  25. msg = s.recv(1)
  26. msg = msg.decode("ascii")
  27. fullMsg += msg
  28.  
  29. print(fullMsg)
  30.  
  31. #Server
  32. import socket
  33. import struct
  34. import random
  35.  
  36. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  37. s.bind((socket.gethostname(), 1032))
  38. s.listen()
  39.  
  40. tries = 0
  41. while True:
  42. connection, address = s.accept()
  43. try:
  44. guess = 0
  45. while(guess == 0):
  46. n = connection.recv(2)
  47. n = struct.unpack("!H", n)[0]
  48. print(f"The client's number{n}")
  49.  
  50. x = random.randint(0, 10)
  51. print(f"The server's number{x}")
  52.  
  53. if x == n:
  54. guess = 1
  55. msg = "You win - within " + str(tries) + " tries"
  56. connection.send("!H", guess)
  57. connection.send(struct.pack("!H", len(msg)))
  58. connection.send(bytes(msg, "ascii"))
  59. else:
  60. tries += 1
  61.  
  62.  
  63.  
  64. finally:
  65. connection.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement