在Chromium 源代码中,提供了建立HTTP Server的代码库。
在原有的net库中,本来提供了net::HttpServer类来实现一个HttpServer. 但是这个类目前已经被放弃。相关功能移动到了
services/network/cpp/public/server中。
deps = [
"//base",
"//net",
"//services/network/:network_service",
"//mojo/core/embedder",
"//mojo/public/cpp/bindings",
"//mojo/public/cpp/system",
"//net:extras",
"//services/network/public/cpp",
"//services/network/public/cpp:buildflags",
"//services/network/public/mojom",
"//services/service_manager/public/cpp",
]
2. 需要一个工作线程来带动
std::unique_ptr<base::Thread> server_thread_ = std::make_unique<base::Thread>("mgr_thread");
server_thread_->StartWithOptions({ base::MessageLoop::TYPE_IO, 0 });
server_thread_->task_runner()->PostTask(FROM_HERE, base::Bind(&run));
3. 需要实现network::HttpServer::Delegate
class Server : public network::server::HttpServer::Delegate{
public:
void OnConnect(int connection_id) override
{
NOTREACHED();
}
void OnHttpRequest(int connection_id, const network::server::HttpServerRequestInfo& info) override
{
NOTREACHED();
}
void OnWebSocketRequest(int connection_id, const network::server::HttpServerRequestInfo& info) override
{
NOTREACHED();
}
void OnWebSocketMessage(int connection_id, std::string data) override
{
NOTREACHED();
}
void OnClose(int connection_id) override
{
NOTREACHED();
}
}
4. 启动Server
void run()
{
mojo::core::Init();
std::unique_ptr<network::server::HttpServer> server_;
std::unique_ptr<net::URLRequestContext> url_request_context_ = std::make_unique<net::URLRequestContext>();
std::unique_ptr<network::SocketFactory> factory_ = std::make_unique<network::SocketFactory>(nullptr, url_request_context_.get());
factory_->CreateTCPServerSocket(
net::IPEndPoint(net::IPAddress::IPv4Localhost(), 10080)
, 1
, TRAFFIC_ANNOTATION_FOR_MXSYNC_REST_SVR
, mojo::MakeRequest(&server_socket_)
, base::BindOnce([](int32_t, const base::Optional<net::IPEndPoint>&) {})
);
server_.reset(new network::server::HttpServer(std::move(server_socket_), this));
}
5. 参考src/services/network/public/cpp/server/http_server_unittest.cc 里面有完整的HttpClient, HttpServer示例。