import struct


def send_msg(sock, msg):
    # Prefix each message with a 4-byte length (network byte order)
    # https://docs.python.org/fr/3.12/library/struct.html#format-characters
    msg = struct.pack('>I', len(msg)) + msg
    try:
        sock.sendall(msg)
    except BrokenPipeError:
        print("The recipient seems disconnected")


def recv_msg(sock):
    # Read message length and unpack it into an integer
    raw_msglen = recvall(sock, 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 = bytearray()
    while len(data) < n:
        packet = sock.recv(n - len(data))
        if not packet:
            return None
        data.extend(packet)
    return data
