2014-04-17 76 views
0

試圖瞭解WINSOCKET的使用Visual C++ 在這裏,我的代碼工作:Winsocket的RESV緩衝區錯誤

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> 

什麼這個東西的交易?

+0

爲什麼在每個字符之後刷新流緩衝區? 不會std :: cout << l <<'\ n'好多了嗎? – jcoder

回答

1

這裏的主要問題是你使用一個字符數組(即使它只是一個單個字符的數組),輸出操作符將其解釋爲一個字符串。正如你應該知道的,所有的字符串都需要被特殊字符'\0'終止,它可以在你閱讀的字符之後的任何內存中。

相反,你應該在接收時使用單一char變量,並使用地址運算符:

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 
} 

我其實推薦這第二個選項。您不但可以檢查錯誤並關閉連接,還可以更有效。