代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <string>
#include <memory>
#include <iostream>
#include "boost/asio.hpp"

class HttpConnect : public std::enable_shared_from_this<HttpConnect>
{
public:
HttpConnect(boost::asio::io_context& io) : m_socket(io) {}
~HttpConnect(){}
void RunOnce()
{
auto sphc = shared_from_this();
boost::asio::async_read_until(m_socket, boost::asio::dynamic_buffer(m_szRequest), "\r\n\r\n",
[sphc, this](const boost::system::error_code& err, size_t length) {
if (err)
{
std::cout << "async_read_until error:" << err.message() << '\n';
return;
}
std::cout << "Request length: " << length << '\n';
std::cout << m_szRequest << '\n';

const char cszHtml[]{ "HTTP/1.0 200 OK\r\n\r\n<html>hello word!!!</html>\r\n" };
boost::asio::async_write(m_socket, boost::asio::buffer(cszHtml), [sphc, this](const boost::system::error_code& err, size_t length){
std::cout << "write length: " << length << '\n';
if (err)
{
std::cout << "async_write error:" << err.message() << '\n';
}
m_socket.close();
}
); // async_write
}
);// async_read_until
}
boost::asio::ip::tcp::socket& Socket() { return m_socket; }
private:
boost::asio::ip::tcp::socket m_socket;
std::string m_szRequest;
};

class SimpleHttpServer
{
public:
SimpleHttpServer(boost::asio::io_context& io, boost::asio::ip::tcp::endpoint ep) : m_ioContext(io), m_acceptor(io, ep) {}
~SimpleHttpServer(){}
void StartAccept()
{
auto sphc = std::make_shared<HttpConnect>(m_ioContext);
m_acceptor.async_accept(sphc->Socket(), [sphc, this](const boost::system::error_code& err) {
if (err)
{
std::cout << "async_accept error:" << err.message() << '\n';
return;
}
sphc->RunOnce();
StartAccept();
}
);// async_accept
}
private:
boost::asio::io_context& m_ioContext;
boost::asio::ip::tcp::acceptor m_acceptor;
};
//
int main()
{
unsigned short nPort{ 8866 };
boost::asio::ip::address address(boost::asio::ip::make_address("127.0.0.1"));

boost::asio::io_context io;
boost::asio::ip::tcp::endpoint ep(address, nPort);
SimpleHttpServer httpServer(io, ep);
httpServer.StartAccept();
io.run();
return 0;
}