【问题标题】:Winsocket resv buffer mistakeWinsock recv 缓冲区错误
【发布时间】:2014-04-17 15:36:45
【问题描述】:

试图了解 Winsocket 与 Visual C++ 的工作原理 这是我的代码:

while (true) {
    char l[1];
    recv(tsock.sock, l, 1, 0);
    std::cout << l << std::endl;
    if (!l)
    {
        return;
    }
}

但是我在尝试获取 google.com:80 http get 查询时得到了什么:

Connected
Sending request to host
H╠╠╠╠╠╠╠╠
T╠╠╠╠╠╠╠╠☺
T╠╠╠╠╠╠╠╠☻
P╠╠╠╠╠╠╠╠♥
/ ╠╠╠╠╠╠╠╠♦
1╠╠╠╠╠╠╠╠♣
.╠╠╠╠╠╠╠╠♠
0╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠
3╠╠╠╠╠╠╠╠
0╠╠╠╠╠╠╠╠

2╠╠╠╠╠╠╠╠♂
╠╠╠╠╠╠╠╠♀
F╠╠╠╠╠╠╠╠
o╠╠╠╠╠╠╠╠♫
u╠╠╠╠╠╠╠╠☼
n╠╠╠╠╠╠╠╠►
d╠╠╠╠╠╠╠╠◄
╠╠╠╠╠╠╠╠↕

╠╠╠╠╠╠╠╠‼
C╠╠╠╠╠╠╠╠¶
...

收到了很多垃圾。但是,当我将缓冲区表格 1 单元格的声明更改为 2 以及更多时,一切似乎都变得更好了。 代码

while (true) {
    char l[2];
    memset(&l, 0, sizeof(l));
    recv(tsock.sock, l, 1, 0);
    std::cout << l << std::endl;
    if (!l)
    {
        return;
    }
}

结果:

ConnectedSending request to hostHTTP / 1.0 302 Found
Cache - Control: private
Content - Type : text / html; charset = UTF - 8
Location: http ://www.google.ru/?gfe_rd=cr&ei=r_RPU4yzJ8GdwAOWjoDoAQ
Content - Length : 258
Date : Thu, 17 Apr 2014 15 : 35 : 11 GMT
Server : GFE / 2.0
Alternate - Protocol : 80 : quic

<HTML><HEAD><meta http - equiv = "content-type" content = "text/html;charset=utf-8">
<TITLE>302 Moved< / TITLE>< / HEAD><BODY>
<H1>302 Moved< / H1>
The document has moved
<A HREF = "http://www.google.ru/?gfe_rd=cr&amp;ei=r_RPU4yzJ8GdwAOWjoDoAQ">here< / A>
.
< / BODY>< / HTML>

这东西是怎么回事?

【问题讨论】:

  • 为什么要在每个字符后刷新流缓冲区? std::cout

标签: c++ sockets visual-c++ winsock


【解决方案1】:

这里的主要问题是您使用了一个字符数组(即使它只是一个单个字符的数组),输出运算符将其解释为字符串。而且您应该知道,所有字符串都需要以特殊字符'\0' 终止,该字符可以在您读取的字符之后的内存中的任何位置。

您应该使用单个char 变量,并在接收时使用address-of 运算符:

char l;
recv(tsock.sock, &l, 1, 0);

或者,您可以使用更大的数组并使用来自recv 的返回值来知道将字符串终止符放在哪里:

char l[1025];  // 1024 +1 for terminator
int rsz = recv(tsock.sock, l, sizeof(l) - 1, 0);  // -1 for terminator
if (rsz > 0)
{
    l[rsz] = '\0';  // Terminate string
    std::cout << l << std::flush;
}
else
{
    // Handle closed connection, or errors
}

我实际上推荐第二个选项。然后,您不仅会检查错误和关闭的连接,而且效率也会更高。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2016-07-17
    相关资源
    最近更新 更多