Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do my simple HTTP server implemented with Boost.ASIO needs sleep to work correctly

I'm trying to write a very simple HTTP server using Boost.Asio. Here is the code (almost the same as the example from Boost.Asio tutorial)

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <thread>
#include <chrono>

using boost::asio::ip::tcp;

int main()
{
    try
    {
        boost::asio::io_service io_service;

        tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 12345));

        for (;;)
        {
            tcp::socket socket(io_service);
            acceptor.accept(socket);

            const char message[] = "HTTP/1.0 200 OK\r\n\r\n<html><body><i>Hello, world</i></body></html>";

            boost::system::error_code ignored_error;
            boost::asio::write(socket, boost::asio::buffer(message), ignored_error);
        }
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

When I run this sample, I try with Chrome at address 127.0.0.1:12345, but it shows "This webpage is not available". But if I start in a debugger and step by step, it correctly displays the italicized "Hello, world". In fact, it will work correctly if I add a line std::this_thread::sleep_for(std::chrono::seconds(1)); after the write operation. What am I doing wrong? Is there a way to avoid this ugly hack?

I'm using Visual Studio 2013 on Windows 7. Compiled as 64 bit code.

like image 330
Siyuan Ren Avatar asked Apr 22 '14 09:04

Siyuan Ren


1 Answers

I think that the problem is an HTTP issue not a networking issue.

The message lacks a Content-Length header and so your HTTP/1.1 client (Chrome) is probably waiting for your server to close the connection to mark the end of the message body, see: rfc2616 section 4.4. Try changing the message to:

  "HTTP/1.0 200 OK\r\nContent-Length: 45\r\n\r\n<html><body><i>Hello, world</i></body></html>";

I hope I've got the Content-Length of your message body right. ;)

like image 130
kenba Avatar answered Sep 23 '22 16:09

kenba