Advertisement
Mac_Pi

binary_messaging.py

Oct 18th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. import pickle # To serialise the data
  2. import socket # To send and receive data
  3.  
  4. HEADER_SIZE = 4 # The amount of bytes used to send the size - a maximum message size of 4,294,967,295 bytes can be represented with 32 bits (4 bytes)
  5.  
  6. # The function used to send binary to the socket
  7. def send_binary(sending_socket, data):
  8.     pickled_data = pickle.dumps(data) # pickle the data - serialise it
  9.     size = len(pickled_data) # Calculate the size of the pickled message
  10.     # Send it to the socket - using + on bytes combines them one after the other.
  11.     sending_socket.send(size.to_bytes(HEADER_SIZE, byteorder="big") + pickled_data)
  12.  
  13. def get_binary(receiving_socket):
  14.    
  15.     # A list to hold any messages from the buffer
  16.     messages = []
  17.    
  18.     # Create the buffer, a binary variable
  19.     buffer = b""
  20.     socket_open = True
  21.     # While the socket has data in it - keep repeating
  22.     while socket_open:
  23.  
  24.         # yield any messages
  25.         for message in messages:
  26.             yield message
  27.         messages = []
  28.  
  29.         # read any data from the socket
  30.         data = receiving_socket.recv(1024)
  31.  
  32.         # if zero data is returned the socket is closed
  33.         if not data:
  34.             socket_open = False
  35.  
  36.         # add the data to the buffer
  37.         buffer += data
  38.         #print(buffer)
  39.        
  40.         processing_buffer = True
  41.         while processing_buffer:
  42.        
  43.             # have we got a header
  44.             if len(buffer) >= HEADER_SIZE:
  45.                 # get the header
  46.                 size = int.from_bytes(buffer[0:HEADER_SIZE], byteorder="big")
  47.  
  48.                 # have we got a complete message
  49.                 if len(buffer) >= HEADER_SIZE + size:
  50.                     # append the message to the list
  51.                     unpickled_message = pickle.loads(buffer[HEADER_SIZE:HEADER_SIZE + size])
  52.                     messages.append(unpickled_message)
  53.                     # strip the message from the buffer
  54.                     buffer = buffer[HEADER_SIZE + size:]
  55.                 else:
  56.                     # there isnt enough data for this message
  57.                     processing_buffer = False
  58.  
  59.             else:
  60.                 # there isnt enough data for a header
  61.                 processing_buffer = False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement