Fetch the repository succeeded.
// asio_echo.cpp —— Boost.Asio / standalone Asio 的 echo 服务器,对比三种执行上下文配置
//
// 编译:g++ -std=c++17 -O2 -pthread -DASIO_STANDALONE asio_echo.cpp -o asio_echo
//
// 用法:./asio_echo <模式> <连接数> <每连接请求数> <服务端线程数>
// 模式 single = 单线程 io_context
// 模式 multi = 多线程 io_context(无 strand)
// 模式 strand = 多线程 io_context + 每连接一个 strand
//
// 说明:本程序的服务端与客户端使用两个独立的 io_context,互不干扰。
// 客户端固定为单线程异步,这样测得的是服务端的处理能力。
#include <asio.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
using namespace std::chrono;
using asio::ip::tcp;
static int pick_port() { return 20000 + (getpid() % 5000); }
// ==================== 服务端 ====================
class Session : public std::enable_shared_from_this<Session> {
public:
// ex 是"这个连接上所有 handler 必须在其上执行"的执行器。
// use_strand=false 时,它就是 io_context 的执行器(多线程下会并发);
// use_strand=true 时,它是 io_context 上派生出的一个 strand(串行)。
Session(tcp::socket s, bool use_strand)
: socket_(std::move(s)),
ex_(use_strand ? asio::any_io_executor(asio::make_strand(socket_.get_executor()))
: asio::any_io_executor(socket_.get_executor())) {}
void start() { do_read(); }
private:
void do_read() {
// bind_executor:规定"回调必须在 ex_ 上执行",这是 Asio 里保证串行的标准做法
socket_.async_read_some(
asio::buffer(buf_, sizeof(buf_)),
asio::bind_executor(ex_, [self = shared_from_this()](
const std::error_code &ec, std::size_t n) {
if (ec) {
std::error_code ig;
self->socket_.shutdown(tcp::socket::shutdown_both, ig);
self->socket_.close(ig);
return;
}
asio::async_write(
self->socket_, asio::buffer(self->buf_, n),
asio::bind_executor(self->ex_, [self](const std::error_code &ec2,
std::size_t) {
if (ec2) { std::error_code ig; self->socket_.close(ig); return; }
self->do_read(); // 继续读下一个请求
}));
}));
}
tcp::socket socket_;
asio::any_io_executor ex_;
char buf_[1024];
};
class Server {
public:
Server(asio::io_context &ctx, unsigned short port, bool use_strand)
: ctx_(ctx),
acceptor_(ctx, tcp::endpoint(asio::ip::make_address("127.0.0.1"), port)),
use_strand_(use_strand) {
do_accept();
}
private:
void do_accept() {
acceptor_.async_accept([this](const std::error_code &ec, tcp::socket s) {
if (!ec) std::make_shared<Session>(std::move(s), use_strand_)->start();
do_accept();
});
}
asio::io_context &ctx_;
tcp::acceptor acceptor_;
bool use_strand_;
};
// ==================== 客户端 ====================
struct Client {
Client(asio::io_context &ctx, unsigned short port, int nreq,
std::atomic<int> &outstanding, std::vector<double> &lat)
: socket_(ctx), nreq_(nreq), outstanding_(outstanding), lat_(lat) {
connect(port);
}
private:
void connect(unsigned short port) {
socket_.async_connect(
tcp::endpoint(asio::ip::make_address("127.0.0.1"), port),
[this](const std::error_code &ec) {
if (ec) { outstanding_--; return; }
t0_ = steady_clock::now();
write_one();
});
}
void write_one() {
if (sent_ >= nreq_) { outstanding_--; std::error_code ig;
socket_.shutdown(tcp::socket::shutdown_both, ig);
socket_.close(ig); return; }
auto self = this;
asio::async_write(socket_, asio::buffer(kMsg, sizeof(kMsg) - 1),
[this, self](const std::error_code &ec, std::size_t) {
if (ec) { outstanding_--; return; }
++sent_;
asio::async_read(socket_, asio::buffer(rbuf_, sizeof(kMsg) - 1),
[this](const std::error_code &ec2, std::size_t) {
if (ec2) { outstanding_--; return; }
lat_.push_back(duration<double, std::milli>(
steady_clock::now() - t0_).count());
write_one(); // 串行:收到响应再发下一个
});
});
}
static constexpr const char *kMsg = "ping\n";
tcp::socket socket_;
int nreq_;
int sent_ = 0;
std::atomic<int> &outstanding_;
std::vector<double> &lat_;
steady_clock::time_point t0_;
char rbuf_[16];
};
int main(int argc, char **argv) {
std::string mode = argc > 1 ? argv[1] : "single";
int nconn = argc > 2 ? std::atoi(argv[2]) : 100;
int nreq = argc > 3 ? std::atoi(argv[3]) : 20;
int nthread = argc > 4 ? std::atoi(argv[4]) : 4;
bool use_strand = (mode == "strand");
int srv_threads = (mode == "single") ? 1 : nthread;
int port = pick_port();
asio::io_context srv_ctx;
Server srv(srv_ctx, (unsigned short)port, use_strand);
// 服务端的所有线程都在后台跑,主线程留给客户端,避免相互干扰
std::vector<std::thread> ths;
for (int i = 0; i < srv_threads; ++i)
ths.emplace_back([&] { srv_ctx.run(); });
// 客户端:独立 io_context,单线程
asio::io_context cli_ctx;
std::atomic<int> outstanding{nconn};
std::vector<double> lat;
lat.reserve((size_t)nconn * nreq);
std::vector<std::unique_ptr<Client>> clients;
for (int i = 0; i < nconn; ++i)
clients.push_back(std::make_unique<Client>(cli_ctx, (unsigned short)port,
nreq, outstanding, lat));
auto t0 = steady_clock::now();
cli_ctx.run();
while (outstanding.load() > 0) std::this_thread::sleep_for(milliseconds(1));
double total = duration<double, std::milli>(steady_clock::now() - t0).count();
srv_ctx.stop();
for (auto &t : ths) t.join();
std::sort(lat.begin(), lat.end());
auto pct = [&](double q) {
return lat.empty() ? 0.0
: lat[std::min((size_t)(lat.size() * q), lat.size() - 1)];
};
std::cout << "模式 = " << mode
<< " 服务端线程数 = " << srv_threads
<< " 连接数 = " << nconn
<< " 总请求数 = " << (nconn * nreq) << "\n"
<< " 完成请求数 " << lat.size() << "\n"
<< " 总耗时 " << total << " ms 吞吐 "
<< (total > 0 ? lat.size() / (total / 1000.0) : 0) << " req/s\n"
<< " 单请求往返延迟 p50=" << pct(0.50) << " ms p99=" << pct(0.99)
<< " ms max=" << (lat.empty() ? 0.0 : lat.back()) << " ms\n\n";
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。