views:

174

answers:

1

I'm having a significant problem using a standard BSD-style socket in a C++ program. In the code below, I connect to a local web server, send a request, and simply create a loop waiting for data to return. I actually do receive the data, but then I get an endless stream of 0-length data as if it was a non-blocking socket. The web server presumably didn't kill the connection, because if so I would have received a length of -1.

Please ignore simple typos I make below, as I'm writing the code from memory, not a direct copy/paste. The code produces the same result on OSX and 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
}
+6  A: 

From the man page of recv

For TCP sockets, the return value 0 means the peer has closed its half
     side of the connection.
Murali VP
When recv() returns 0, the connection was closed; but if you want to poll (or wait on) the socket for incoming data, check out the man page for select().
Chris
Wow thanks, I guess that was a misunderstand on my part, but why would it close the connection if I specified "keep-alive"?
oskar