At work I am taking on some development stuff on the beaglebone black and I have to learn Python. I've had a blast so far!!

So I'm trying to understand what some of the code is doing. I have a sample script that opens a port and listens for connections (the server side), and I read through the code and I get to this:

#Receiving from client
data = conn.recv(4096)

What I am trying to understand is what the 4096 number is doing. I have googled around and found things like this: https://docs.python.org/2/library/socket.html

Which tell me that it's a buffer size, should be a relatively small power of 2, like 4096.

socket.recv(bufsize[, flags])

In all honesty, I still have no clue what it's doing.

So does it simply buffer the data stream as it comes out - and the data stream could be a single byte or many MB of data?
Does the 4096 bytes mean I can't receive more than 4096 bytes of data at a time? To get more than 4096 do I need to make a loop to read 4096 byte chunks of data as the data is being sent?

The code seems to work just fine, but I want to know what that 4096 actually means.

Thanks

In CPython, Socket.recv() is implemented by calling the C function

ssize_t recv(int sockfd, void *buf, size_t len, int flags);

You can see this by downloading the python source code and looking into socketmodule.c, or online here. Before calling the C function, python allocates a buffer which capacity is bufsize (4096 in your case).

The documentation says

The maximum amount of data to be received at once is specified by bufsize

It means that a single call can not receive more than 4096 bytes at a time and you need to make a loop to read more.

It may look strange, but the socket module is a low level module and its main purpose is to make the C socket api available to python programs.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.