I have experience programming sockets using the Berkeley Socket APIs in C. Typically, any socket programming requires a strategy that lets the receiving socket know how much data it should receive. This can be done with header fields or delimiters. Generally, I prefer a header field that contains a length.
Of course, we also need to know the size of the length header field itself, which is just a fixed size value that must be agreed upon by both the sender and the receiver. In C, this is easy to implement, since native integer types are fixed in size and in binary format, so you can just say something like:
uint16_t bytes_to_receive; recv(sock, &bytes_to_receive, sizeof(bytes_to_receive), 0); bytes_to_receive = ntohs(bytes_to_receive);
But how is this idiom done using Python sockets? In Python, integers are objects and pickled integers are arrays of variable-length bytes. Therefore, we cannot use a pickled integer as a length header field, because we cannot be sure of its size in bytes.
Of course, I could always send a byte array of a known size containing a binary integer, such as b'\x05\x00' , to create a 16-bit binary integer with a value of 5 in a small trailing format, but it really doesn't seem like the right approach .
So how is this usually done in Python?
c python sockets
Channel72
source share