user21806805
user21806805

Reputation:

My image comes out broken from tcp sending

I'm a beginner in C++, and I'm building a program to transfer files and images. I have a simple code to send pictures over TCP taken from Sending Picture via TCP. But my images came broken, with missing parts.

I'm using DEV C++ 5.11.0.0

It also outputs the following warning:

[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]

This is my code:

SERVER:

int recive(SOCKET socket){

    int n = 0;

    cout << "Reading image size" << endl;
    char buf[50];
    int siz = 0;
  
    if ((n = recv(socket, buf, sizeof(buf), 0) <0)){
        perror("recv_size()");
        exit(errno);
    }
       
    siz = atoi(buf);
    cout << siz << endl; 

    char Rbuffer[siz];
    cout << "Reading image byte array" << endl;
    n = 0;
       
    if ((n = recv(socket, Rbuffer, siz, 0)) < 0){
    perror("recv_size()");
    exit(errno);
}

cout << "Converting byte array to image" << endl;
FILE *image;
image = fopen("recu.jpg", "wb");
fwrite(Rbuffer, sizeof(char), siz, image);
fclose(image);
cout << "done" << endl;
    
}

CLIENT:

int send(SOCKET socket){

    int n = 0;
    int siz = 0;
    FILE *picture;
    char buf[50];
    char *s="";

    cout << "Getting image size" << endl;
    picture = fopen("test.png", "rb"); 
    fseek(picture, 0, SEEK_END);
    siz = ftell(picture);
    cout << siz << endl; 

    cout << "Sending picture size to the server" << endl;
    sprintf(buf, "%d", siz);
    if((n = send(socket, buf, sizeof(buf), 0)) < 0)
    {
            perror("send_size()");
            exit(errno);
    }

    char Sbuf[siz];
    cout << "Sending the picture as byte array" << endl;
    fseek(picture, 0, SEEK_END);
    siz = ftell(picture);
    fseek(picture, 0, SEEK_SET); 


    while(!feof(picture)){
        n = fread(Sbuf, sizeof(char), siz, picture);
        if (n > 0) {
            if((n = send(socket, Sbuf, siz, 0)) < 0)
            {
                perror("send_data()");
                exit(errno);
            }
        }

    }
 
}

The image that gets into the Client:

INPUT

The image that comes out Server:

OUTPUT

Upvotes: 0

Views: 51

Answers (0)

Related Questions