开发者

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 soluti开发者_运维百科on. 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?


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.


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 );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜