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

标签 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
}

最佳答案

来自 recv 的手册页

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

关于c++ - 为什么阻塞套接字会重复返回 0 长度数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1735179/

相关文章:

c - 弹性错误 matchtype.h

.net - 在 .NET 中测试本地 Intranet 中的连接时应该使用什么端口号?

C++防止浮点寄存器在页面错误处理程序中被清零

c++ - 前向声明 boost.type_erasure 引用类型

c++ - 四叉树遍历

c++ - 配置 Visual Studio 2008 以在程序/库中使用 log4cxx

c - 访问传递给 realloc 的指针

c - 在 Win32 中,大小成员 (cb) 名称的实际含义是什么?

android - 通过wireshark查看android网络流量

java - 在 HttpUrlConnection 中设置自定义套接字实现