Advertisement
Guest User

client

a guest
May 30th, 2025
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. import socket
  2. import _pickle as pickle
  3.  
  4.  
  5. class Network:
  6. """
  7. class to connect, send and recieve information from the server
  8. need to hardcode the host attirbute to be the server's ip
  9. """
  10. def __init__(self):
  11. self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  12. #self.client.settimeout(10.0)
  13. self.host = "192.168.0.105"
  14. self.port = 5555
  15. self.addr = (self.host, self.port)
  16.  
  17. def connect(self, name):
  18. """
  19. connects to server and returns the id of the client that connected
  20. :param name: str
  21. :return: int reprsenting id
  22. """
  23. self.client.connect(self.addr)
  24. self.client.send(str.encode(name))
  25. val = self.client.recv(8)
  26. return int(val.decode()) # can be int because will be an int id
  27.  
  28. def disconnect(self):
  29. """
  30. disconnects from the server
  31. :return: None
  32. """
  33. self.client.close()
  34.  
  35. def send(self, data, pick=False):
  36. """
  37. sends information to the server
  38.  
  39. :param data: str
  40. :param pick: boolean if should pickle or not
  41. :return: str
  42. """
  43. try:
  44. if pick:
  45. self.client.send(pickle.dumps(data))
  46. else:
  47. self.client.send(str.encode(data))
  48. reply = self.client.recv(2048*4)
  49. try:
  50. reply = pickle.loads(reply)
  51. except Exception as e:
  52. print(e)
  53.  
  54. return reply
  55. except socket.error as e:
  56. print(e)
  57.  
  58.  
  59.  
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement