Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket
- import struct
- import pickle
- import time
- localhost_with_port_9000 = ( "127.0.0.1", 9000 )
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
- server_socket.bind( localhost_with_port_9000 )
- server_socket.listen( 1 )
- print("\nWaiting for client connection...")
- connection, address = server_socket.accept()
- with connection as conn:
- print(f"connected by {address}")
- # 1. Test one data payload dividing into three transmission to client
- data_1 = {"message":"hello world. This is test item #1's data"}
- data_1_rawbyte = pickle.dumps(data_1)
- id = 1
- payload = data_1_rawbyte
- # definition of header
- # first field is id
- # second field is size of payload
- header = (id, len(payload) )
- # define header size as 2 * 4 Unsigne Int = 8 Bytes
- header_rawbyte_1 = struct.pack("!2I", *header)
- # divide one data payload into three transmission
- send_1_full = header_rawbyte_1 + payload
- send_1_a = send_1_full[:5]
- send_1_b = send_1_full[5:10]
- send_1_c = send_1_full[10:]
- # send 1_a to clinet
- print("\n send data 1_a to clinet ... ")
- connection.sendall( send_1_a )
- time.sleep(0.5)
- # send 1_b to clinet
- print("\n send data 1_b to clinet ... ")
- connection.sendall( send_1_b )
- time.sleep(0.5)
- # send 1_c to clinet
- print("\n send data 1_c to clinet ... ")
- connection.sendall( send_1_c )
- time.sleep(0.5)
- # ---------------------------------------------------------
- ## 2. Test merging two differnt data payload divide into one transmission to client
- data_2 = {"message":"Meow meow. This is test item #2's data"}
- data_2_rawbyte = pickle.dumps(data_2)
- id = 2
- payload = data_2_rawbyte
- # definition of header
- # first field is id
- # second field is size of payload
- header = (id, len(payload) )
- # define header size as 2 * 4 Unsigne Int = 8 Bytes
- header_rawbyte_2 = struct.pack("!2I", *header)
- data_3 = {"message":"Meow meow. This is test item #3's data", "demand":"quit connection"}
- data_3_rawbyte = pickle.dumps(data_3)
- id = 3
- payload = data_3_rawbyte
- # definition of header
- # first field is id
- # second field is size of payload
- header = (id, len(payload) )
- # define header size as 2 * 4 Unsigne Int = 8 Bytes
- header_rawbyte_3 = struct.pack("!2I", *header)
- send_2_and_3 = header_rawbyte_2 + data_2_rawbyte + header_rawbyte_3 + data_3_rawbyte
- # send 2 and 3 to clinet
- print("\n send data 2 and data 3 in one transmission to clinet ... ")
- connection.sendall( send_2_and_3 )
- time.sleep(0.5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement