我应该在 C++ 中使用什么作为缓冲区?用于从网络套接字接收数据?
我正在使用带有 C++ 的套接字。该程序只是请求一个 HTTP 页面,将其读入缓冲区 buf[512]
,然后显示该缓冲区。然而,页面可以包含比缓冲区更多的数据,因此如果没有剩余空间,它将被切断。我可以增大缓冲区大小,但这似乎不是一个好的解决方案。这是我正在使用的代码:
char buf[512];
int byte_count = recv(sockfd, buf, sizeof(buf), 0);
What would be a replacement to a char array in C++ to use as a buffer?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
取决于您打算如何处理数据。如果您只想将其转储到输出流,那么正确的做法是做您正在做的事情,但要循环执行,直到没有更多数据可供读取,每次之后将缓冲区写入输出流读。
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.
基本上没有 - 当使用 recv 时,您需要重复调用它,直到它读取您的所有输入。您当然可以使用支持不断增长的缓冲区的更高级的套接字库,但对于普通的旧式 recv(),您需要一个 char 数组(或 char 向量)。
当然,您可以将读取的数据附加到动态缓冲区中,例如字符串:
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: