【发布时间】: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&ei=r_RPU4yzJ8GdwAOWjoDoAQ">here< / A>
.
< / BODY>< / HTML>
这东西是怎么回事?
【问题讨论】:
-
为什么要在每个字符后刷新流缓冲区? std::cout
标签: c++ sockets visual-c++ winsock