使用C ++套接字仅接收必要的数据 [英] Receiving only necessary data with C++ Socket

查看:62
本文介绍了使用C ++套接字仅接收必要的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想获取带有其标题的页面内容...但是似乎我的大小为1024的缓冲区对于通过的最后一个信息包来说太大还是太小...我不知道如果有道理的话,不要想得太多或太少.这是我的代码.它可以打印出所有信息的页面,但我想确保它是正确的.

I'm just trying to get the contents of a page with their headers...but it seems that my buffer of size 1024 is either too large or too small for the last packet of information coming through...I don't want to get too much or too little, if that makes sense. Here's my code. It's printing out the page just fine with all the information, but I want to ensure that it's correct.

//Build HTTP Get Request
std::stringstream ss;
ss << "GET " << url << " HTTP/1.0\r\nHost: " << strHostName << "\r\n\r\n";
std::string req = ss.str();

// Send Request
send(hSocket, req.c_str(), strlen(req.c_str()), 0);

// Read from socket into buffer.
do
{
     nReadAmount = read(hSocket, pBuffer, sizeof pBuffer);
     printf("%s", pBuffer);

}
while(nReadAmount != 0);

推荐答案

 nReadAmount = read(hSocket, pBuffer, sizeof pBuffer);
 printf("%s", pBuffer);

这是坏的.您只能将%s 格式说明符用于C样式(以零结尾)的字符串. printf 应该如何知道要打印多少字节?该信息位于 nReadAmount 中,但您不使用它.

This is broken. You can only use the %s format specifier for a C-style (zero-terminated) string. How is printf supposed to know how many bytes to print? That information is in nReadAmount, but you don't use it.

此外,即使 read 失败,也会调用 printf .

Also, you call printf even if read fails.

最简单的解决方法:

 do
 {
     nReadAmount = read(hSocket, pBuffer, (sizeof pBuffer) - 1);
     if (nReadAmount <= 0)
         break;
     pBuffer[nReadAmount] = 0;
     printf("%s", pBuffer);
 } while(1);

这篇关于使用C ++套接字仅接收必要的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆