How to stop blocking at recv() in C++ (Not VC++.NET)
A snippet of my code is here :
void getFile(SOCKET c_socket)
{
char *memblock;
int num_of_bytes,file_buf = 100000; //any user specific number of bytes
memblock = new char [file_buf];
//dest file
ofstream dest("c:\\dest\\umg.rar",ios::app | ios::binary);
while(true)
{
//reading "num_of_bytes" byte(s) from sourcefile
num_of_bytes = recv( c_socket, memblock, file_buf, 0 );
//writing "num_of_bytes" byte(s) to destination file
dest.write(memblock,num_of_bytes);
//last bunch of bytes recieved
if(num_of_bytes == 0) break;
}
//closing source and destination files.
dest.close();
printf("\n The file was successfully copied.\n");
delete memblock;
//system("pause");
return;
}
here the while loop never terminates and the control again reaches to the recv() function.
When i see the file in this case(i.e. when the control is inside the loop and the program still running) it is not copied at the server and some bytes are remaining. And when i closed the Client apllication, the remaining bytes were copied to the file at the server end.
One of my friend told me that some bytes are still in the client buffer which are copied to the file and when i close the client application, those remaining bytes from the buffer are copied to the file. To eliminate this he told me to use this condition instead :
//last bunch of bytes recieved
if(num_of_bytes < file_buf) break;
so this worked fine. But he still says that i should have flushed the socket buffer instead(both at the client end and server end ), either before sending the bytes or after receiving.
Secondly,
when my friend told me the
//last bunch of bytes recieved
if(num_of_bytes < file_buf) break;
condition, I thought that when the file with exactly the same size will come, then what will happen?
So if I don't use this way, then what can I do? How can I prevent the loop to block at recv().
He also told me that I can send any dummy value like "OK" or "DONE" etc... when all the bytes of the file have been sent from the client end, I tried this but my Server was unable to understand this dummy value, so it again blocked at recv(). I am not getting any other way, please show me some way. Will I Have to flush the buffer or use some other way to stop the server from blocking at the recv().
Please Help.
Pawan

