def recvall(s, n):
    """ recv() n bytes, otherwise raise a ValueError """
    buflist = []
    got = 0

    while got < n:
        buf = s.recv(n-got)
        if not buf:
            break
        buflist.append(buf)
        got += len(buf)

    data = ''.join(buflist)

    if got != n:
        raise ValueError('got {} bytes, expected {}'.format(got, n), data)

    return data