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.