Skip to content

头文件和类成员 ​

c++
#include "boost/beast/core.hpp"
#include "boost/beast/http.hpp"
#include "boost/beast/version.hpp"
#include "boost/beast/websocket.hpp"

using asio = boost::asio
using http = booost::beast::http
//临时请求
http::request<http::string_body> _request;
http::response<http::dynamic_body> _response;
//8k缓冲区
boost::beast::flat_buffer _buffer{8192};
//tcp socket
asio::ip::tcp::socket _socket;

//定时器
asio::steady_timer deadline_{
    _socket.get_executor(), std::chrono::seconds(60) 
};

接收http报文 ​

c++
void Session::ProcessRequest() {
  _response.version(_request.version());
  _response.keep_alive(true);

  switch (_request.method()) {
  case http::verb::get:
    _response.result(http::status::ok);
    _response.set(http::field::server, "Beast");
    if (_request.target() == "/") {
      _response.set(http::field::content_type, "text/html");
      boost::beast::ostream(_response.body())
          << "<html>\n"
          << "<head><title>Welcome to my http server!</title></head>\n"
          << "<body>\n"
          << "</body>\n"
          << "</html>\n";
    } else {
      _response.result(http::status::not_found);
      _response.set(http::field::content_type, "text/plain");
      boost::beast::ostream(_response.body()) << "File not found\r\n";
    }
    break;

  default:
    // We return responses indicating an error if
    // we do not recognize the request method.
    _response.result(http::status::bad_request);
    _response.set(http::field::content_type, "text/plain");
    boost::beast::ostream(_response.body())
        << "Invalid request-method '" << std::string(_request.method_string())
        << "'";
    break;
  }

  WriteResponse();
}

发送http报文 ​

c++
void Session::WriteResponse() {
  auto self = shared_from_this();
  _response.content_length(_response.body().size());
  http::async_write(
      _socket, _response, [self](boost::beast::error_code ec, std::size_t) {
        self->_socket.shutdown(asio::ip::tcp::socket::shutdown_send, ec);
        self->deadline_.cancel();
      });
}

学 习 记 录