dsuveges

Untitled

Jul 26th, 2021
1,111
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import json
  2. import socket
  3. import time
  4.  
  5. class Client():
  6.  
  7.     HOST = "127.0.0.1"
  8.     PORT = 30001
  9.     PACKET_SIZE = 110000
  10.  
  11.     def __init__(self, host: str = None, port: int = None, packet_size: int = None) -> None:
  12.  
  13.         self.host = host if host else self.HOST
  14.         self.port = port if port else self.PORT
  15.         self.packet_size = packet_size if packet_size else self.PACKET_SIZE
  16.  
  17.         try:
  18.             # Creating socket:
  19.             self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  20.            
  21.             # Connect:
  22.             self.socket.connect((self.host, self.port))
  23.            
  24.         except ConnectionRefusedError:
  25.             raise ConnectionRefusedError(f'Could not connect to {self.host} on port {self.port}')
  26.            
  27.         print('Connection was successful!')
  28.  
  29.     def close_socket(self) -> None:
  30.         self.socket.close()
  31.  
  32.     def get_status(self) -> str:
  33.         response = self.socket.recv(self.PACKET_SIZE)
  34.         response = response.strip()
  35.  
  36.         try:
  37.             data = json.loads(response)
  38.         except JSONDecodeError:
  39.             raise JSONDecodeError(f'data could not be parsed as json: {data}')
  40.  
  41.         try:
  42.             status = data['data']['status']
  43.         except KeyError:
  44.             raise KeyError(f"keys: ['data']['status'] were not found in data: {data}")
  45.  
  46.         return status
  47.  
  48. client = Client()
  49.  
  50. while True:
  51.     time.sleep(2)
  52.     print(client.get_status())
  53.  
  54. client.close_socket()
RAW Paste Data