pythonpython-2.7socketsselectaudio

Socket chunk/buffer size


I’m using select on a socket connection in Python with a chunk size of 1024 to send two wav files. The server is listening to two sockets which are both sending chunks of 1024 (checked with print statement). The chunk data is then put into an empty numpy array for further processing however, when I check the size of the numpy array, the value is only 512 for each array, leading to a combined 1024 chunk on the receiving end and resulting in distorted audio. I’ve tried adjusting chunk size, as well as using

data = s.recv(1024)
data += s.recv(1024)

Which results in both sizes being 1024, however the audio ends up being sped up. Can provide code upon request. Any help is much appreciated!


Solution

  • TCP is a byte streaming protocol. You are guaranteed to get the bytes in the same order sent, but not in the same chunk sizes as sent. Use (or design) a higher level protocol (HTTP, etc.) to ensure you receive all the bytes sent.

    For example, the first bytes sent could be the null-terminated file name followed by the file size as a null-terminated string, followed by the file contents. On accepting the connection, the receiver buffers s.recv(1024) calls and extracts the file name and file size terminated by nulls, then continues reading until the buffer contains at least "file size" bytes.

    Another option is to just transmit the file and close the connection, the receiver buffers everything received until recv() returns zero bytes, indicating the connection was closed.

    The first option allows for sending multiple files without closing the connection.