It might be that, when reading from a stream-based socket, you are not getting all the bytes you think you are getting. Then you are writing a file of the correct size, but only the beginning of the file will have any meaningful data.
If you are using TCP (a stream-oriented connection), when you go to read from the socket into a buffer (you are probably using a byte/char array), you will only get all the bytes which are available at the time of the call. The call to the reading function will return immediately but the buffer into which the data is written will only be partially full.
To fix this, you will need to check how many bytes were actually read from the socket (usually the reading call will return that number), and then repeatedly read from the socket until you have all the bytes you need.
Update
With regards to your code, it certainly looks like you only make one call to recv()
and do not check to make sure the entire file was transferred. You will need to put this in a loop and continuously read data until you have read as much as you want to (in this case, the size of the entire file).
You may also want to fix this problem on the sending side. Even though you have the sleep command between calls to send
, send
will only send a certain amount of data per call. You will need to place send
in a loop and keep sending data until you have sent all the data you wish to send.
Consider the following (untested pseudo-)code for recv
:
int numberOfReceivedBytes=0;
while (numberOfReceivedBytes<fileSize){
numberOfReceivedBytes+=recv(newSocket,buffer + numberOfReceivedBytes,sizeof(*buffer),0)
}
Furthermore, it looks like when you read the file size from the socket, you may accidentally get part of the file itself in addition to the size of the file. Make sure you know exactly how many bytes will indicate the actual size of the file and read only that many bytes. Also, atoi
only works for the string (ASCII) representation of a number. Your server is receiving the actual number.
To do sending:
int numberOfSentBytes=0;
while (numberOfSentBytes<fileSize){
numberOfSentBytes+=send(newSocket,buffer+numberOfSentBytes,fileSize-numberOfSentBytes+1,0);
}