Search code examples
c++filesocketstcprecv

C++ | TCP - receive


i need help... i spend much time to write a tcp connection to transfer an image from server to client.

The problem is, that it looks like that the client didnt receive all bytes.

Server output:

Anfrage erhalten: img_size...Imagesize sended!
Anfrage erhalten: image...Start
1024 bytes send (1)
2048 bytes send (2)
3072 bytes send (3)
...

Client output:

Get Imagesize: 75186 bytes
(0) 75186 
(0) (0/75186)
(1) (5/75186)
(2) (80/75186)
.
.
.
(16150/75186)
(16227/75186)

at this moment the client wait forever... if number (1) was sended number (1) is received with 5 bytes?!?!?! WWHHHYYY?

Here my Client code:

tcp.Send( "image" );
msg = "";

while( msg.length() < size_img ){
    cout << "(" << msg.length() << "/" << size_img << ")" << endl;

    if( msg.length() + 1024 < size_img ){
        g = tcp.receive(1024);
    }else{
        g = tcp.receive(size_img - msg.length());
    }

    ss << msg;
    ss << g;
    msg = ss.str();
    ss.str("");
}

string TCPClient::receive(int size)
{
char buffer[size];
memset(&buffer[0], 0, sizeof(buffer));

size_t len = sizeof(buffer);
char *p = buffer;
ssize_t n;

string reply;

while(len > 0 && (n=recv(sock,p,len,0)) > 0){
    p += n;
    len -= (size_t)n;
}
if ( len > 0 || n < 0 ) {
    cout << "receive failed!" << endl;
    return nullptr;
}
//buffer[size-1]='\0';
reply = buffer;
return reply;
}

Server Send function:

void TCPServer::Send_Bytes(unsigned char* msg, int laenge)
{
for(int i = 0; i < laenge; i=i+1024){
    if(i+1024 < laenge){
        send(newsockfd,msg+i,1024,0);
    }else{
        send(newsockfd,msg+i,laenge - i,0);
        break;
    }
    cout << i << endl;

    usleep(100000);
}

}

Please help me... i dont know how to handel that?!?!?

yacobs ;)


Solution

  • Solution:

    void TCPClient::receive_char(char* outStr, int size){
        char buffer[size];
        memset(&buffer[0], 0, sizeof(buffer));
    
        size_t len = sizeof(buffer);
        char *p = buffer;
        ssize_t n;
    
        while(len > 0 && (n=recv(sock,p,len,0)) > 0){
            p += n;
            len -= (size_t)n;
        }
        if ( len > 0 || n < 0 ) {
            cout << "receive failed!" << endl;
        }
        //buffer[size-1]='\0';
        for(int i=0; i < size; ++i){
            outStr[i] = buffer[i];
        }   
    }
    

    You can call with:

    char data[4096];
    memset(&data[0], 0, sizeof(data));
    
    tcp.receive_char(data,4096);
    
    for(int i = 0; i < 4096; i++){
        image_bytes[counter] = data[i];
        counter++;
    }
    

    Maybe there are better solutions... :D