Advertisement
cuteSquirrel

client.py

Mar 26th, 2021
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. import socket
  2. import struct
  3. import pickle
  4.  
  5. localhost_with_port_9000 = ( "127.0.0.1", 9000 )
  6.  
  7. # Recall:
  8. # header size is 2 * 4 Unsigne Int = 8 Bytes
  9. # header_rawbyte = struct.pack("!2I", *header), defined in server code
  10.  
  11. HEADER_SIZE = 8
  12.  
  13.  
  14. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
  15.  
  16.     client_socket.connect( localhost_with_port_9000 )
  17.  
  18.     print(f"connect to {localhost_with_port_9000} ...")
  19.  
  20.     # read buffer for client
  21.     buffer = bytes()
  22.  
  23.     while True:
  24.  
  25.         # receive data bytes on network from server
  26.         raw_bytes = client_socket.recv(512)
  27.  
  28.         if raw_bytes:
  29.  
  30.             buffer += raw_bytes
  31.  
  32.             while True:
  33.  
  34.                 if len(buffer) < HEADER_SIZE:
  35.                     print("\n Keep reading until full rawbytes of header is read \n")
  36.                     break
  37.                
  38.                 # decode and recover header from rawbytes
  39.                 header = struct.unpack('!2I', buffer[:HEADER_SIZE])
  40.  
  41.                 # definition of header
  42.                 # first field is id
  43.                 # second field is size of payload
  44.                 id, payload_size = header
  45.  
  46.                 if len(buffer) < (HEADER_SIZE + payload_size):
  47.  
  48.                     print("\n Keep reading until buffer size is long enough to decode payload \n")
  49.                     break
  50.  
  51.                 payload_rawbyte = buffer[HEADER_SIZE: HEADER_SIZE+payload_size ]
  52.  
  53.                 # decode and recover data from payload rawbytes
  54.                 data = pickle.loads( payload_rawbyte )
  55.                
  56.                 print("\nDecode is successful")
  57.                 print(f"id = {id}")
  58.                 print(f"data = {data} \n")
  59.  
  60.                 if data.get("demand", "") == "quit connection":
  61.                     print("\n Client get quit connection message from server \n")
  62.                     exit(0)
  63.  
  64.                 # discard old data in buffer
  65.                 buffer = buffer[HEADER_SIZE+payload_size:]
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement