为什么阻塞套接字会重复返回0长度数据?

时间:2009-11-14 18:49:12

标签: c++ c networking network-programming sockets

我在使用C ++程序中的标准BSD样式套接字时遇到了严重问题。在下面的代码中,我连接到本地Web服务器,发送请求,并简单地创建一个等待数据返回的循环。我实际上接收数据,但随后我得到了无穷无尽的0长度数据流,好像它是一个非阻塞套接字。 Web服务器可能不会终止连接,因为如果是这样的话,我会收到-1的长度。

请忽略我在下面做的简单拼写错误,因为我正在从内存中编写代码,而不是直接复制/粘贴。该代码在OSX和Windows上产生相同的结果。

int sock = socket(AF_INET, SOCK_STREAM, 0);

//assume serv_addr has been created correctly
connect(sock, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0);

std::string header = "GET / HTTP/1.1\r\n"
    "Host: 127.0.0.1:80\r\n"
    "Keep-Alive: 300\r\n"
    "Connection: keep-alive\r\n\r\n";

send(sock, header.c_str(), header.length()+1, 0);

for (;;) {
    char buffer[1024];
    int len = recv(sock, buffer, 1024, 0);
    cout << len << endl;
    //this outputs two numbers around 200 and 500,
    //which are the header and html, and then it
    //outputs and endless stream of 0's
}

1 个答案:

答案 0 :(得分:6)

来自recv的手册页

For TCP sockets, the return value 0 means the peer has closed its half
     side of the connection.