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


I am trying to write a very simple HTTP server using Boost.Asio. This is the code (almost like the example from Boost. ASIO Tutorial)

  #include & lt; Iostream & gt; #include & lt; String & gt; # Include & lt; boost / asio.hpp & gt; #include & lt; Thread & gt; # Include & lt; Chrono & gt; 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  Object body & lt; i & gt; Hello, world & lt; / i & Gt; & lt; / body & gt; & lt; / html & gt; "; Boost :: system :: error_code ignored_error; Promotion :: ASIO :: Write (socket, boost :: aso :: buffer (message), ignored_uper); }} Hold (std :: exception & e) {std :: cerr & lt; & Lt; E.what () & lt; & Lt; Std :: endl; } Return 0; }   

When I run this sample, I try on the Chrome 127.0.0.1:1222345 address, but it shows "this webpage is not available". But if I start with a debugger and step-by-step, then it is italic "Halo, World" displays correctly, if I have a line std :: this_thread :: sleep_for ( Std :: chrono :: seconds (1)), then it will work correctly; What do I do wrong after writing? Is there any way to avoid this ugly hack?

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

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

The content-length header in the message and therefore your HTTP / 1.1 client (chrome) might possibly mark your body end of the message body Waiting for connection to close, see: Section 4.4. Try changing the message to:

  "HTTP / 1.0 200 OK \ r \ n Content-Length: 45 \ r \ n \ r \ n  & lt; ; Body & gt; & lt; i & gt; Hello, World & lt; / i & gt; & lt; / body & gt; & lt; / html & gt; ";   

I hope that I have found your message body's Content-Length ;)

Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -