计算机网络 / 系统课时
io_uring跑通一个异步Echo服务
io_uring跑通一个异步Echo服务
这一节用一个最小 TCP Echo 服务把 accept、recv、send 和完成事件串起来。重点不是堆高级特性,而是先建立可靠的连接状态机:每个完成事件都能找到对应连接,并决定下一次应提交什么操作。
学习目标
- 用 liburing 提交异步
accept、recv与send请求,并从 CQE 读取结果。 - 为每个连接维护缓冲区、待发送长度和偏移,正确处理断开与部分发送。
- 通过本地客户端验证“接收完成后发送、发送完成后继续接收”的闭环。
完成事件如何驱动连接
io_uring 通过提交队列把 I/O 请求交给内核,再通过完成队列把结果交回用户态;应用处理的是“这次请求已经完成以及结果是什么”,而不是先收到可读通知再主动调用 recv。CQE 的 res 通常承载成功字节数或负的错误码。([Man7][1])
Echo 连接可以收敛成很小的状态循环:接受连接后只挂一个接收请求;接收得到字节后提交发送;发送可能只完成一部分,因此用偏移继续提交剩余数据;全部发送完成后才重新提交接收。对于流式 socket,同一方向同时挂多个相互依赖的 send 或 recv 可能产生顺序问题,因此这个最小实验坚持“每个方向最多一个在途操作”。([Man7][2])

实现最小 Echo 服务
下面的程序使用一个 conn 保存连接缓冲区与发送进度,用一个 op 标记 CQE 对应的是接受、接收还是发送。所有缓冲区都放在连接对象中,因此在异步操作完成前不会离开作用域。
#include <arpa/inet.h>
#include <errno.h>
#include <liburing.h>
#include <netinet/in.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define QUEUE_DEPTH 256
#define BUF_SIZE 4096
enum op_kind { OP_ACCEPT, OP_RECV, OP_SEND };
/* 连接对象必须存活到对应 I/O 完成,缓冲区也因此保持有效。 */
struct conn {
int fd;
char buf[BUF_SIZE];
size_t len;
size_t off;
};
struct op {
enum op_kind kind;
struct conn *conn;
};
static void die(const char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
static struct io_uring_sqe *next_sqe(struct io_uring *ring) {
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
if (!sqe) {
fprintf(stderr, "submission queue is full\n");
exit(EXIT_FAILURE);
}
return sqe;
}
static struct op *new_op(enum op_kind kind, struct conn *conn) {
struct op *op = calloc(1, sizeof(*op));
if (!op)
die("calloc");
op->kind = kind;
op->conn = conn;
return op;
}
static void submit_accept(struct io_uring *ring, int listen_fd) {
/* 始终维持一个 accept 请求,完成后立即补上下一个。 */
struct io_uring_sqe *sqe = next_sqe(ring);
struct op *op = new_op(OP_ACCEPT, NULL);
io_uring_prep_accept(sqe, listen_fd, NULL, NULL, SOCK_CLOEXEC);
io_uring_sqe_set_data(sqe, op);
}
static void submit_recv(struct io_uring *ring, struct conn *c) {
/* 同一连接只挂一个 recv,避免覆盖仍在使用的接收缓冲区。 */
struct io_uring_sqe *sqe = next_sqe(ring);
struct op *op = new_op(OP_RECV, c);
io_uring_prep_recv(sqe, c->fd, c->buf, sizeof(c->buf), 0);
io_uring_sqe_set_data(sqe, op);
}
static void submit_send(struct io_uring *ring, struct conn *c) {
/* off 记录部分发送后的进度,只提交尚未发送的区间。 */
struct io_uring_sqe *sqe = next_sqe(ring);
struct op *op = new_op(OP_SEND, c);
io_uring_prep_send(
sqe,
c->fd,
c->buf + c->off,
c->len - c->off,
MSG_NOSIGNAL
);
io_uring_sqe_set_data(sqe, op);
}
static void close_conn(struct conn *c) {
close(c->fd);
free(c);
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s <PORT>\n", argv[0]);
return EXIT_FAILURE;
}
char *end = NULL;
errno = 0;
long port = strtol(argv[1], &end, 10);
if (errno || *end != '\0' || port < 1 || port > 65535) {
fprintf(stderr, "invalid port\n");
return EXIT_FAILURE;
}
int listen_fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (listen_fd < 0)
die("socket");
int one = 1;
if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
die("setsockopt");
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_addr.s_addr = htonl(INADDR_ANY),
.sin_port = htons((uint16_t)port),
};
if (bind(listen_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
die("bind");
if (listen(listen_fd, 128) < 0)
die("listen");
struct io_uring ring;
int rc = io_uring_queue_init(QUEUE_DEPTH, &ring, 0);
if (rc < 0) {
errno = -rc;
die("io_uring_queue_init");
}
submit_accept(&ring, listen_fd);
rc = io_uring_submit(&ring);
if (rc < 0) {
errno = -rc;
die("io_uring_submit");
}
printf("listening on 0.0.0.0:%ld\n", port);
fflush(stdout);
for (;;) {
/* 每个 CQE 都通过 user_data 找回操作类型和连接状态。 */
struct io_uring_cqe *cqe;
rc = io_uring_wait_cqe(&ring, &cqe);
if (rc < 0) {
errno = -rc;
die("io_uring_wait_cqe");
}
struct op *op = io_uring_cqe_get_data(cqe);
int res = cqe->res;
if (op->kind == OP_ACCEPT) {
submit_accept(&ring, listen_fd);
if (res >= 0) {
struct conn *c = calloc(1, sizeof(*c));
if (!c)
die("calloc");
c->fd = res;
submit_recv(&ring, c);
} else {
fprintf(stderr, "accept: %s\n", strerror(-res));
}
} else if (op->kind == OP_RECV) {
struct conn *c = op->conn;
if (res <= 0) {
close_conn(c);
} else {
c->len = (size_t)res;
c->off = 0;
submit_send(&ring, c);
}
} else {
struct conn *c = op->conn;
if (res <= 0) {
close_conn(c);
} else {
c->off += (size_t)res;
if (c->off < c->len)
submit_send(&ring, c);
else
submit_recv(&ring, c);
}
}
free(op);
io_uring_cqe_seen(&ring, cqe);
rc = io_uring_submit(&ring);
if (rc < 0) {
errno = -rc;
die("io_uring_submit");
}
}
}预期结果
程序编译并启动后持续监听指定端口;客户端发送的字节会被原样回显。这个实现故意不使用 multishot、固定缓冲区或 SQPOLL,便于先看清最基本的完成链。recv 完成前不能改写 conn.buf;send 完成前也不能把同一段数据覆盖成下一条消息。
编译、运行与验证
需要 Linux 环境、C 编译器以及已安装的 liburing 开发库。保存为 echo_uring.c 后编译:
cc -O2 -Wall -Wextra echo_uring.c -luring -o echo_uring预期结果
编译成功时不输出内容,并生成 echo_uring 可执行文件。运行时输入一个实际未占用端口;下文用 <PORT> 表示你输入的值:
read -r -p 'PORT: ' PORT
./echo_uring "$PORT"预期输出
listening on 0.0.0.0:<PORT>另开一个 Bash 终端,输入同一个端口后发送一行文本:
read -r -p 'PORT: ' PORT
exec 3<>"/dev/tcp/127.0.0.1/$PORT"
printf 'hello io_uring\n' >&3
IFS= read -r line <&3
printf '%s\n' "$line"
exec 3>&-预期输出
hello io_uring如果连接成功但没有回显,先检查 CQE 的 res:recv 为正数才应进入发送;send 的正数结果还要与剩余长度比较,不能假设一次就写完。若初始化阶段直接失败,则先确认当前 Linux 内核允许使用 io_uring,并确认程序链接到可用的 liburing。
状态管理不能省略
完成驱动并不等于“不需要状态”。恰恰相反,CQE 只告诉你某个请求完成了,应用仍要知道这个请求属于哪个连接、下一步是什么、缓冲区能否复用。这个最小 Echo 服务把状态压缩到 fd、buf、len、off 四项,已经足够暴露异步网络编程最关键的工程约束:资源生命周期必须覆盖整个在途 I/O,并且每个完成事件都要能确定唯一的后续动作。