#!/usr/bin/python3

import random
import socket
import struct
import time


def get_data(s, size):
    data = b""
    while size > 0:
        chunk = 64 * 1024
        if size < chunk:
            chunk = size
        block = s.recv(chunk)
        if len(block) == 0:
            raise RuntimeError("no data")
        size -= len(block)
        data += block
    return data


s = socket.socket()
s.connect(("127.0.0.1", 9000))
s.send(struct.pack("<Q", 0xffffffffffffffff))

sleep_after = 10
while True:
    headers = s.recv(16)
    (key, size) = struct.unpack("<QQ", headers)
    print("Key = {0} size = {1}".format(key, hex(size)))
    data = get_data(s, size)
    if len(data) != size:
        print("Insufficient data received, asked for {0}, got {1}".format(size, len(data)))

    sleep_after -= 1

    if sleep_after <= 0:
        time.sleep(float(random.randint(0, 15)))
        sleep_after = 100
