我正在使用nghttp2
. 我试图弄清楚为什么
调用on_data
中的处理程序server.cpp
两次。我知道它被调用了两次,因为当我发送一个包含数据的请求时,我得到了服务器中单个请求的以下日志输出。
1
2
但是如果我不在请求中发送数据。单个请求的日志输出是我所期望的
1
我使用客户端和这行代码将数据发送到服务器
auto req = sess.submit(ec, "GET", "http://127.0.0.1:3000/", "aaaaaaaaaa");
为了不发送数据,我只需删除第三个参数。
server.cpp
编译g++ server.cpp -o server.out -lnghttp2_asio -lboost_system -lcrypto -lpthread -lssl -lboost_thread
#include <iostream>
#include <nghttp2/asio_http2_server.h>
using namespace nghttp2::asio_http2;
using namespace nghttp2::asio_http2::server;
int main() {
std::string hostname = "127.0.0.1";
std::string port = "3000";
boost::system::error_code ec;
http2 server;
int count = 0;
server.handle("/", [&count](const request &req, const response &res) {
req.on_data([&res, &count](const uint8_t *data, std::size_t len) {
std::cerr << ++count << '\n';
res.write_head(200);
res.end("done");
});
});
if (server.listen_and_serve(ec, hostname, port)) {
std::cerr << "error: " << ec.message() << std::endl;
}
}
编译g++ client.cpp -o client.out -lnghttp2_asio -lboost_system -lcrypto -lpthread -lssl -lboost_thread
#include <iostream>
#include <nghttp2/asio_http2_client.h>
using boost::asio::ip::tcp;
using namespace nghttp2::asio_http2;
using namespace nghttp2::asio_http2::client;
int main(int argc, char *argv[]) {
boost::system::error_code ec;
boost::asio::io_service io_service;
// connect to localhost:3000
session sess(io_service, "127.0.0.1", "3000");
sess.on_connect([&sess](tcp::resolver::iterator endpoint_it) {
boost::system::error_code ec;
auto req = sess.submit(ec, "GET", "http://127.0.0.1:3000/", "aaaaaaaaaa");
req->on_response([](const response &res) {
// print status code and response header fields.
std::cerr << "HTTP/2 " << res.status_code() << std::endl;
for (auto &kv : res.header()) {
std::cerr << kv.first << ": " << kv.second.value << "\n";
}
std::cerr << std::endl;
res.on_data([](const uint8_t *data, std::size_t len) {
std::cerr.write(reinterpret_cast<const char *>(data), len);
std::cerr << std::endl;
});
});
req->on_close([&sess](uint32_t error_code) {
// shutdown session after first request was done.
sess.shutdown();
});
});
sess.on_error([](const boost::system::error_code &ec) {
std::cerr << "error: " << ec.message() << std::endl;
});
io_service.run();
}