One simple way to transfer a file over a socket is for the sender to first send a 4-byte (32-bit) integer indicating the size of the file, then send the bytes of the file. (If the file can be more than 4GB, you might instead change the "protocol" to send a 64-bit integer first, then followed by the file data.)
The receiving side would first read the 4-byte integer. Given that it now knows how many bytes to expect, it would then read on the socket until it receives exactly that many bytes. (While reading chunk-by-chunk, it would be writing the bytes to an opened output file.)
The socket.SendCount and socket.ReceiveCount methods are helpers that could be used in sending a 4-byte integer count.
answered Mar 01 '13 at 09:50