import struct
import socket

def send_msg(sock, msg):
    # Prefix each message with a 4-byte length (network byte order)
    msg = str(msg)
    msg = struct.pack('>I', len(msg)) + msg.encode()
    sock.sendall(msg)

def send_cmd(sock, msg):
    msg = msg + ' '*(1024 - len(msg))
    sock.send((msg.encode()))

def recv_msg(sock):
    # Read message length and unpack it into an integer
    raw_msglen = sock.recv(4)
    if not raw_msglen:
        return None
    msglen = struct.unpack('>I', raw_msglen)[0]
    # Read the message data
    return recvall(sock, msglen)

def recvall(sock, n):
    # Helper function to recv n bytes or return None if EOF is hit
    data = ''
    while len(data.encode()) < n:
        packet = sock.recv(n - len(data))
        if not packet:
            return None
        data = packet.decode()
    return data
