Spreadsheet
Spreadsheet

Reputation: 267

What should I use as a buffer in C++ for receiving data from network sockets?

I'm using sockets with C++. The program simply requests an HTTP page, reads it into a buffer buf[512], and then displays the buffer. However pages can contain more data than the buffer, so it will cut off if there is no more space left. I can make the buffer size bigger, but that doesn't seem like a good solution. This is the code that I am using:

char buf[512];
int byte_count = recv(sockfd, buf, sizeof(buf), 0);

What would be an alternative to a char array in C++ to use as a buffer?

Upvotes: 2

Views: 1836

Answers (2)

anon
anon

Reputation:

There basically isn't one - when using recv, you need to call it repeatedly until it has read all your input. You can of course use more advanced sockets libraries that support growing buffers, but for plain old recv(), a n array of char (or vector of char) is what you need.

You can of course append the data you read into a dynamic buffer such as a string:

string page;
while( len = recv( ... ) ) {
   page.append( buf, len );
}

Upvotes: 1

Mike Baranczak
Mike Baranczak

Reputation: 8374

Depends on what you intend to do with the data. If you just want to dump it to an output stream, then the proper thing to do is to do what you're doing, but do it in a loop until there's no more data to read, writing the buffer to the output stream after each read.

Upvotes: 2

Related Questions