Advertisement
Guest User

Untitled

a guest
Feb 26th, 2020
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. HOST = '127.0.0.1'
  2. PORT = 3000
  3. SIZE = 1000
  4. HEADERSIZE = 10
  5. WORKERS = 2
  6.  
  7. conn = None
  8. addr = None
  9. soc = None
  10. order_m = None
  11.  
  12.  
  13. def create_connection():
  14.     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  15.     s.bind((HOST, PORT))
  16.     s.listen()
  17.     global conn, addr
  18.     global soc
  19.     soc = s
  20.     conn, addr = s.accept()
  21.  
  22.  
  23. def send_object(data):
  24.     if soc is None:
  25.         raise NotImplementedError  # There is no connection
  26.     else:
  27.         # make data as bytes
  28.         global conn
  29.         msg = pickle.dumps(data)
  30.         msg = bytes(f"{len(msg):<{HEADERSIZE}}", 'utf-8') + msg
  31.         conn.send(msg)
  32.  
  33.  
  34. def get_object():
  35.     global conn
  36.     if conn is None:
  37.         raise NotImplementedError  # There is no connection
  38.     else:
  39.         # unpickle the data
  40.         data = b''
  41.         while True:
  42.             part = conn.recv(SIZE)
  43.             data += part
  44.             if len(part) < SIZE:
  45.                 break
  46.         full_msg = data
  47.         try:
  48.             data = pickle.loads(full_msg[HEADERSIZE:])
  49.         except EOFError:
  50.             data = None
  51.         return data
  52.  
  53.  
  54. def main():
  55.     create_connection()
  56.     # Initialize objects
  57.     global order_m
  58.     ing_map = Ingredient_map()
  59.     order_m = OrderManager()
  60.  
  61.     while True:
  62.         msg = get_object()
  63.         if msg is None:
  64.             pass
  65.         elif msg.req == Request.G_ING_MAP:  # get ingredient map
  66.             send_object(ing_map.instance.map)
  67.         elif msg.req == Request.P_ORDER:
  68.             order_m.add_order(msg.data)
  69.             print(msg.data)
  70.  
  71.     # end while
  72.     soc.close()
  73.  
  74.  
  75. if __name__ == "__main__":
  76.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement