Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket
- import struct
- import pickle
- localhost_with_port_9000 = ( "127.0.0.1", 9000 )
- # Recall:
- # header size is 2 * 4 Unsigne Int = 8 Bytes
- # header_rawbyte = struct.pack("!2I", *header), defined in server code
- HEADER_SIZE = 8
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
- client_socket.connect( localhost_with_port_9000 )
- print(f"connect to {localhost_with_port_9000} ...")
- # read buffer for client
- buffer = bytes()
- while True:
- # receive data bytes on network from server
- raw_bytes = client_socket.recv(512)
- if raw_bytes:
- buffer += raw_bytes
- while True:
- if len(buffer) < HEADER_SIZE:
- print("\n Keep reading until full rawbytes of header is read \n")
- break
- # decode and recover header from rawbytes
- header = struct.unpack('!2I', buffer[:HEADER_SIZE])
- # definition of header
- # first field is id
- # second field is size of payload
- id, payload_size = header
- if len(buffer) < (HEADER_SIZE + payload_size):
- print("\n Keep reading until buffer size is long enough to decode payload \n")
- break
- payload_rawbyte = buffer[HEADER_SIZE: HEADER_SIZE+payload_size ]
- # decode and recover data from payload rawbytes
- data = pickle.loads( payload_rawbyte )
- print("\nDecode is successful")
- print(f"id = {id}")
- print(f"data = {data} \n")
- if data.get("demand", "") == "quit connection":
- print("\n Client get quit connection message from server \n")
- exit(0)
- # discard old data in buffer
- buffer = buffer[HEADER_SIZE+payload_size:]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement