试图了解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查询时,我得到了什么:
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>
这件事怎么办?
最佳答案
这里的主要问题是您使用了一个字符数组(即使它只是单个字符的数组),其输出运算符也将其解释为字符串。如您所知,所有字符串都必须以特殊字符'\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
}
我实际上建议第二种选择。然后,您不仅可以检查错误和关闭的连接,而且效率更高。
关于c++ - Winsock Recv缓冲区错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23137419/