1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
| // echo_single.c — 单连接 Echo Server
// 编译:gcc -std=c11 -O2 echo_single.c -luring -o echo_single
#include <liburing.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define BUF_SIZE 1024
// 请求类型枚举
enum EventType {
EVENT_ACCEPT = 0,
EVENT_READ = 1,
EVENT_WRITE = 2,
};
int main()
{
int listenFd = socket(AF_INET, SOCK_STREAM, 0);
int opt = 1;
setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(9000),
.sin_addr.s_addr = INADDR_ANY,
};
bind(listenFd, (struct sockaddr *)&addr, sizeof(addr));
listen(listenFd, 128);
struct io_uring ring;
io_uring_queue_init(32, &ring, 0);
// 提交 accept 请求
struct io_uring_sqe *sqe = io_uring_get_sqe(&ring);
io_uring_prep_accept(sqe, listenFd, NULL, NULL, 0);
// 用 user_data 编码事件类型
io_uring_sqe_set_data64(sqe, EVENT_ACCEPT);
io_uring_submit(&ring);
char buf[BUF_SIZE];
int clientFd = -1;
printf("Echo Server 监听端口 9000...\n");
while (1) {
struct io_uring_cqe *cqe;
io_uring_wait_cqe(&ring, &cqe);
__u64 eventType = io_uring_cqe_get_data64(cqe);
switch (eventType) {
case EVENT_ACCEPT: {
clientFd = cqe->res;
if (clientFd < 0) {
fprintf(stderr, "accept 失败: %s\n", strerror(-clientFd));
break;
}
printf("新连接: fd=%d\n", clientFd);
// 提交 recv 请求
sqe = io_uring_get_sqe(&ring);
io_uring_prep_recv(sqe, clientFd, buf, BUF_SIZE, 0);
io_uring_sqe_set_data64(sqe, EVENT_READ);
io_uring_submit(&ring);
break;
}
case EVENT_READ: {
if (cqe->res <= 0) {
// 连接关闭或出错
printf("连接关闭 (fd=%d)\n", clientFd);
close(clientFd);
// 重新提交 accept
sqe = io_uring_get_sqe(&ring);
io_uring_prep_accept(sqe, listenFd, NULL, NULL, 0);
io_uring_sqe_set_data64(sqe, EVENT_ACCEPT);
io_uring_submit(&ring);
break;
}
int bytesRead = cqe->res;
printf("收到 %d 字节: %.*s", bytesRead, bytesRead, buf);
// 提交 send 请求(回显数据)
sqe = io_uring_get_sqe(&ring);
io_uring_prep_send(sqe, clientFd, buf, bytesRead, 0);
io_uring_sqe_set_data64(sqe, EVENT_WRITE);
io_uring_submit(&ring);
break;
}
case EVENT_WRITE: {
if (cqe->res < 0) {
fprintf(stderr, "send 失败: %s\n", strerror(-cqe->res));
close(clientFd);
break;
}
printf("回显 %d 字节\n", cqe->res);
// send 完成后,继续 recv
sqe = io_uring_get_sqe(&ring);
io_uring_prep_recv(sqe, clientFd, buf, BUF_SIZE, 0);
io_uring_sqe_set_data64(sqe, EVENT_READ);
io_uring_submit(&ring);
break;
}
}
io_uring_cqe_seen(&ring, cqe);
}
io_uring_queue_exit(&ring);
close(listenFd);
return 0;
}
// 测试:
// 终端1: ./echo_single
// 终端2: nc localhost 9000
// 输入 "hello"
// 收到 "hello"
|