Daeto
Daeto

Reputation: 480

c - client server socket programming - sending files

I am having trouble sending and receiving files while working with sockets in C.

Let's say I have a file that is 2,463 bytes big and I want to send it from client to server but it never sends the entire file.

I've been searching the internet for a while now but couldn't find a solution so I'd be very glad if someone could tell me how to make this work.

Here is my code:

Client:

char buffer[256];

bzero(buffer, 256);

int block_size;

while(1){

block_size = fread(buffer, sizeof(char), sizeof(buffer), fs); // read from the file 

if (block_size == 0){

break;

}

if (block_size < 0){

perror("ERROR: Failed while sending data.");
exit(EXIT_FAILURE);

break;

}

void *p = buffer;

while (block_size > 0) {

int bytes_written = write(clientSocket, buffer, block_size); // send the data to server 

if (bytes_written <= 0) {

perror("ERROR: Failed while sending data.");
exit(EXIT_FAILURE);

}

block_size -= bytes_written;
p += bytes_written;

}

bzero(buffer, 256);

}

Server:

bzero(buffer, 256);

int file_block_size = 0;

while (1){

bzero(buffer, 256);

file_block_size = read(incoming_socket, buffer,255); // read the data from client

fwrite(buffer, sizeof(char), file_block_size, fr); // write the data to file

if (file_block_size == 0 || file_block_size < 256){

fwrite(buffer, sizeof(char), file_block_size, fr);

break;

}

}

As I've said, this never sends the entire file that is for example 2,463 bytes big, only a portion of it.

Thanks in advance, will be glad for any help I can get.

Upvotes: 0

Views: 2507

Answers (1)

user5159806
user5159806

Reputation: 92

You need to pair your read with a write. As in the current state your client code will send only the result of your last read operation since you are overwriting the contents of your buffer on each read.

Try something like this on the client side:

char buffer[256];
size_t bytes_read = 0;
ssize_t bytes_written = 0;
do{
    bytes_read = fread(buffer, sizeof(char), sizeof(buffer), fs);
    if(ferror(fs))
    {
        perror("Error while reading from file.");
        close(clientSocket);
        fclose(fs);
        exit(EXIT_FAILURE);
    }
    bytes_written = write(clientSocket, buffer, bytes_read);
    printf("Write operation status: %s; bytes sent: %d\n", strerror(errno), bytes_written);
} while(!feof(fs) && bytes_written != -1);

And on the server side I would do:

char buffer[256];
ssize_t bytes_read = 0;
while((bytes_read = read(incoming_socket, buffer, sizeof(buffer))) > 0)
{
   printf("%d bytes read\n", bytes_read);
   fwrite(buffer, sizeof(char), bytes_read, fr);
   if(ferror(fr))
   {
       perror("Error while writing to file");
       close(incoming_socket);
       fclose(fr);
       exit(EXIT_FAILURE);
   }
}
if(bytes_read == -1)
    printf("%s\n", strerror(errno));

Upvotes: 1

Related Questions