How to read exactly N bytes from stdin in Native Messaging host?

Since a single socket read could easily be short (and can also be longer than expected - messages can be grouped together), you’ll need a read buffer. But you’re working with stdin, not a plain socket, so it’s possible you can actually use the buffer that already exists. In general, though, the way to read precisely N bytes is like this:

sock = <whatever>
buffer = b""
def read(n):
    while len(buffer) < n:
        data = sock.read(len(buffer) - n)
        if not data: return # failed read, other end gone
        buffer += data
    ret, buffer = buffer[:n], buffer[n:]
    return ret

This is suitable for most messaging formats. You might be able to shortcut some parts of this, but the loop is probably necessary regardless.