0

我正在使用nghttp2_asio。我使用./configure --enable-asio-lib. 然后,我添加/usr/local/lib/etc/ld.so.conf文件中。代码如下:

#include "bits/stdc++.h"
#include "nghttp2/asio_http2_server.h"

using namespace std;
using namespace nghttp2::asio_http2;
using namespace nghttp2::asio_http2::server;

int main(int argc, char **argv) {
  http2 srv;
  srv.num_threads(4);
  srv.handle("/", [](const request &req, const response &res) {
    cout << req.uri().path << endl;
    header_map headers;
    headers.emplace("content-type", header_value{ "text/html", false });
    res.write_head(200, headers);
    res.end(file_generator("index.html"));
  });
  boost::system::error_code ec;
  if (srv.listen_and_serve(ec, "localhost", "8080")) cerr << ec.message() << endl;
  return 0;
}

当我尝试在 上打开浏览器(Chrome 或 Firefox)时http://localhost:8080,出现以下错误:

此页面不工作

localhost没有发送任何数据。

ERR_EMPTY_RESPONSE

即使我尝试使用curl,它也会给我错误:

curl:(52)来自服务器的空回复

唯一有效的是curl http://localhost:8080 --http2-prior-knowledge.

有解决方案吗?

4

1 回答 1

1

您的浏览器似乎拒绝通过未加密的连接执行 HTTP/2。维基百科页面有以下说法

尽管标准本身不需要使用加密,[51] 所有主要客户端实现(Firefox、[52] Chrome、Safari、Opera、IE、Edge)都表示它们将仅支持基于 TLS 的 HTTP/2,这使得加密实际上是强制性的。 [53]

cURL 有一个不同的问题:它默认为 HTTP/1,您的 HTTP/2 服务器无法理解。添加标志使其直接使用 HTTP/2 二进制协议。或者,连接到 HTTPS 端点将自动打开 HTTP/2。

有关如何使用加密服务的示例,请参阅libnghttp2_asio 文档

int main(int argc, char *argv[]) {
  boost::system::error_code ec;
  boost::asio::ssl::context tls(boost::asio::ssl::context::sslv23);

  tls.use_private_key_file("server.key", boost::asio::ssl::context::pem);
  tls.use_certificate_chain_file("server.crt");

  configure_tls_context_easy(ec, tls);

  http2 server;

  // add server handlers here

  if (server.listen_and_serve(ec, tls, "localhost", "3000")) {
    std::cerr << "error: " << ec.message() << std::endl;
  }
}
于 2021-07-12T12:21:52.430 回答