Index

Reading or sending data on a TCP socket looks simple, but it can be tricky. read(2) & write(2) don’t have to consume the whole data they get. If you call read on a socket requesting a billion bytes, you’ll probably get less.

If you need to read a set number of bytes, you’ll have to repeat calls until you have all the data you want. Here’s an example of such loop in Python:

def readall(sock, count):
    r = bytes()
    while count:
        x = sock.recv(count)

        if x == '': # End of file
            raise ...

        r += x
        count -= len(x)
    return r

In Python sockets have a sendall method which does more or less that, but there’s no recvall method. There’s another method: the socket.makefile() function creates a file-like object for the socket. With this file-like object there’s no need to loop to get the whole buffer back:

sock = socket.create_connection(...)

f = sock.makefile()
x = f.read(1234) # Will return a 1234 characters long string

You must make sure buffering is enabled for this to work.

PS: NOTE that calling read/write on a socket is basically the same a calling it with recv/send without flags.