I am using Linux. C2 (client) should read and send contents of file F1.txt to C1 (server) in successive messages of size 256 bytes (or remaining size of the file when you get near the end of the file)
First, I get the F1.txt size in bytes and sent it to the server c1.
fseek(fp, 0L, SEEK_END); //move fp to the end of the file
int fileLen = ftell(fp); // get the file size because ftell returns the current value of the position indicator
fseek(fp, 0L, SEEK_SET); //seek back to the begin of the file
write(sock, &fileLen, sizeof(int)); //send file size to server c1
Next, I send the file in successive 256 bytes by a for loop. The client c2 code is
char buffer[BUF_SIZE] = {0}; //BUF_SIZE=256
for (int i = 0; i <((fileLen/256) +1); i++)
{
memset(buffer, 0, sizeof(buffer)); //clear buffer
fread(buffer, 1, i <(fileLen/256)?(sizeof(buffer)):(fileLen%256), fp); // read BUF_SIZE elements, each one with a size of 1 bytes,
printf("Message client_c2 sent: %s\n", buffer);
write(sock, buffer, i <(fileLen/256)?sizeof(buffer):(fileLen%256));
usleep(1000);
}
fclose(fp);
The server c1 read the filesize, and read the socket within the for loop:
int receiveFileLen;
read(clnt_sock, &receiveFileLen, sizeof(int));
printf("clinet_c2 file size is %d\n",receiveFileLen);
for (int i = 0; i < ((receiveFileLen/256) +1); i++)
{
memset(buffer, 0, sizeof(buffer)); //clear buffer
read(clnt_sock, buffer, i < (receiveFileLen/256) ? sizeof(buffer) :(receiveFileLen%256) );
printf("buffer that writen into file is %s\n",buffer);
fwrite(buffer, strlen(buffer), 1,fp);
}
(1) The problem is in client c2 code's fread(fp), when i printf("Message client_c2 sent: %s\n", buffer); I found every time at the end of buffer, there is a wrong char (square shape in which shows 0002.)
(2) In server c1 code. I read the socket and fwrite it to a local txt. fwrite(buffer, strlen(buffer), 1,fp); I tried strlen(buffer)+1
, but it gives me wrong chars ^B in the txt, so I use strlen(buffer).
(3) In server c1 code, I cannot read the full content of the remaining size of the file when I get near the end of the file. In the for loop, I get the previous iterations correctly written into txt, but when comes to the last iteration, i = (receiveFileLen/256) in other words, only part of socket content is read and fwrite into the txt, there is still chars that should be read remaining in the socket.
Thank you for your help!