Silvia B
Silvia B

Reputation: 45

How to receive big data with recv() function using c++?

I'm writing a console application using c++ which using sockets and send an HTTP GET request to a server but the response is an html file bigger than 1000000 infact my buffer: char buffer[1000000]; is too small. I need to receive bigger data from the server than the size of buffer.

I use this code but what is the way to receive a bigger response? I'm a beginner in this programming area so please help me with code and explenations thanks:

char buffer[1000000];


    int nDataLength;
    while ((nDataLength = recv(Socket, buffer, 1000000, 0)) > 0) {
        int i = 0;

        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
            myString += buffer[i];
            i += 1;
        }
    }

    cout << myString << "\n"; 

Upvotes: 0

Views: 5987

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595712

You need to use a smaller fixed length buffer when reading from the socket, and then append the received data to a dynamically growing buffer (like a std::string, or a file) on each loop iteration. recv() tells you how many bytes were actually received, do not access more than that many bytes when accessing the buffer.

char buffer[1024];
std::string myString;

int nDataLength;
while ((nDataLength = recv(Socket, buffer, sizeof(buffer), 0)) > 0) {
    myString.append(buffer, nDataLength);
}

std::cout << myString << "\n"; 

Upvotes: 3

Kim Ryunghi
Kim Ryunghi

Reputation: 66

recv return value is total size of receved data. so you can know total data size, if your buffer is smaller than total data size there is 2 solutions. I guess... 1. allocate buffer on the heap. using like new, allcoc etc. 2. store received data to data structure(like circular queue, queue) while tatal data size is zero(recv function return)

I prefer to use 2nd solution. Googling about recv function , socket programming sample codes. That'll helpfull.

Upvotes: 1

Related Questions