|
1 | 1 | const std = @import("std"); |
2 | 2 | const builtin = @import("builtin"); |
3 | | -const net = std.net; |
4 | | -const windows = std.os.windows; |
5 | | -const linux = std.os.linux; |
6 | | - |
7 | | -// POLLIN, POLLERR, POLLHUP, POLLNVAL 均是 poll 的事件 |
8 | | - |
9 | | -/// windows context 定义 |
10 | | -const windows_context = struct { |
11 | | - const POLLIN: i16 = 0x0100; |
12 | | - const POLLERR: i16 = 0x0001; |
13 | | - const POLLHUP: i16 = 0x0002; |
14 | | - const POLLNVAL: i16 = 0x0004; |
15 | | - const INVALID_SOCKET = windows.ws2_32.INVALID_SOCKET; |
16 | | -}; |
17 | | - |
18 | | -/// linux context 定义 |
19 | | -const linux_context = struct { |
20 | | - const POLLIN: i16 = 0x0001; |
21 | | - const POLLERR: i16 = 0x0008; |
22 | | - const POLLHUP: i16 = 0x0010; |
23 | | - const POLLNVAL: i16 = 0x0020; |
24 | | - const INVALID_SOCKET = -1; |
25 | | -}; |
26 | | - |
27 | | -/// macOS context 定义 |
28 | | -const macos_context = struct { |
29 | | - const POLLIN: i16 = 0x0001; |
30 | | - const POLLERR: i16 = 0x0008; |
31 | | - const POLLHUP: i16 = 0x0010; |
32 | | - const POLLNVAL: i16 = 0x0020; |
33 | | - const INVALID_SOCKET = -1; |
34 | | -}; |
35 | | - |
36 | | -const context = switch (builtin.os.tag) { |
37 | | - .windows => windows_context, |
38 | | - .linux => linux_context, |
39 | | - .macos => macos_context, |
40 | | - else => @compileError("unsupported os"), |
41 | | -}; |
| 3 | +const Io = std.Io; |
| 4 | +const net = Io.net; |
42 | 5 |
|
43 | 6 | pub fn main() !void { |
44 | 7 | // #region listen |
45 | | - // 解析地址 |
46 | | - const port = 8080; |
47 | | - const address = try net.Address.parseIp4("127.0.0.1", port); |
| 8 | + // 初始化 Threaded I/O 后端(单线程模式) |
| 9 | + var threaded: Io.Threaded = .init_single_threaded; |
| 10 | + defer threaded.deinit(); |
| 11 | + const io = threaded.io(); |
| 12 | + |
| 13 | + // 解析地址并监听 |
| 14 | + const port: u16 = 8080; |
| 15 | + const address: net.IpAddress = .{ .ip4 = .loopback(port) }; |
| 16 | + |
48 | 17 | // 初始化一个server,这里就包含了 socket() 和 bind() 两个过程 |
49 | | - var server = try address.listen(.{}); |
50 | | - defer server.deinit(); |
| 18 | + var server = try address.listen(io, .{ .reuse_address = true }); |
| 19 | + defer server.deinit(io); |
51 | 20 | // #endregion listen |
52 | 21 |
|
53 | | - // #region data |
54 | | - // 定义最大连接数 |
55 | | - const max_sockets = 1000; |
56 | | - // buffer 用于存储 client 发过来的数据 |
57 | | - var buf: [1024]u8 = std.mem.zeroes([1024]u8); |
58 | | - // 存储 accept 拿到的 connections |
59 | | - var connections: [max_sockets]?net.Server.Connection = undefined; |
60 | | - // sockfds 用于存储 pollfd, 用于传递给 poll 函数 |
61 | | - var sockfds: [max_sockets]if (builtin.os.tag == .windows) |
62 | | - windows.ws2_32.pollfd |
63 | | - else |
64 | | - std.posix.pollfd = undefined; |
65 | | - // #endregion data |
66 | | - for (0..max_sockets) |i| { |
67 | | - sockfds[i].fd = context.INVALID_SOCKET; |
68 | | - sockfds[i].events = context.POLLIN; |
69 | | - connections[i] = null; |
70 | | - } |
71 | | - sockfds[0].fd = server.stream.handle; |
72 | | - |
73 | 22 | std.log.info("start listening at {d}...", .{port}); |
74 | 23 |
|
75 | | - // 无限循环,等待客户端连接或者已连接的客户端发送数据 |
| 24 | + // 无限循环,等待客户端连接 |
76 | 25 | while (true) { |
77 | | - // 调用 poll,nums 是返回的事件数量 |
78 | | - var nums = if (builtin.os.tag == .windows) windows.poll(&sockfds, max_sockets, -1) else try std.posix.poll(&sockfds, -1); |
79 | | - if (nums == 0) { |
80 | | - continue; |
81 | | - } |
82 | | - // 如果返回的事件数量小于0,说明出错了 |
83 | | - // 仅仅在 windows 下会出现这种情况 |
84 | | - if (nums < 0) { |
85 | | - @panic("An error occurred in poll"); |
86 | | - } |
87 | | - |
88 | | - // NOTE: 值得注意的是,我们使用的模型是先处理已连接的客户端,再处理新连接的客户端 |
| 26 | + // #region new-connection |
| 27 | + // 等待新的连接 |
| 28 | + std.log.info("waiting for client...", .{}); |
| 29 | + const stream = try server.accept(io); |
| 30 | + std.log.info("new client connected!", .{}); |
| 31 | + // #endregion new-connection |
89 | 32 |
|
90 | 33 | // #region exist-connections |
91 | | - // 遍历所有的连接,处理事件 |
92 | | - for (1..max_sockets) |i| { |
93 | | - // 这里的 nums 是 poll 返回的事件数量 |
94 | | - // 在windows下,WSApoll允许返回0,未超时且没有套接字处于指定的状态 |
95 | | - if (nums == 0) { |
| 34 | + // 处理客户端数据(简化版本:一次处理一个客户端) |
| 35 | + // 初始化读写缓冲区 |
| 36 | + var read_buffer: [4096]u8 = undefined; |
| 37 | + var write_buffer: [4096]u8 = undefined; |
| 38 | + var reader = stream.reader(io, &read_buffer); |
| 39 | + var writer = stream.writer(io, &write_buffer); |
| 40 | + |
| 41 | + while (true) { |
| 42 | + // 读取客户端发送的数据 |
| 43 | + // 使用 peekGreedy(1) 获取至少 1 字节,返回所有可用数据 |
| 44 | + const data = reader.interface.peekGreedy(1) catch |err| { |
| 45 | + if (err == error.EndOfStream) { |
| 46 | + std.log.info("client disconnected", .{}); |
| 47 | + break; |
| 48 | + } |
| 49 | + if (reader.err) |read_err| { |
| 50 | + std.log.err("read error: {}", .{read_err}); |
| 51 | + } |
96 | 52 | break; |
97 | | - } |
98 | | - const sockfd = sockfds[i]; |
99 | | - |
100 | | - // 检查是否是无效的 socket |
101 | | - if (sockfd.fd == context.INVALID_SOCKET) { |
102 | | - continue; |
103 | | - } |
104 | | - |
105 | | - // 由于 windows 针对无效的socket也会触发POLLNVAL |
106 | | - // 当前 sock 有 IO 事件时,处理完后将 nums 减一 |
107 | | - defer if (sockfd.revents != 0) { |
108 | | - nums -= 1; |
109 | 53 | }; |
110 | 54 |
|
111 | | - // 检查是否是 POLLIN 事件,即是否有数据可读 |
112 | | - if (sockfd.revents & (context.POLLIN) != 0) { |
113 | | - const c = connections[i]; |
114 | | - if (c) |connection| { |
115 | | - const len = try connection.stream.read(&buf); |
116 | | - // 如果连接已经断开,那么关闭连接 |
117 | | - // 这是因为如果已经 close 的连接,读取的时候会返回0 |
118 | | - if (len == 0) { |
119 | | - // 但为了保险起见,我们还是调用 close |
120 | | - // 因为有可能是连接没有断开,但是出现了错误 |
121 | | - connection.stream.close(); |
122 | | - // 将 pollfd 和 connection 置为无效 |
123 | | - sockfds[i].fd = context.INVALID_SOCKET; |
124 | | - std.log.info("client from {any} close!", .{ |
125 | | - connection.address, |
126 | | - }); |
127 | | - connections[i] = null; |
128 | | - } else { |
129 | | - // 如果读取到了数据,那么将数据写回去 |
130 | | - // 但仅仅这样写一次并不安全 |
131 | | - // 最优解应该是使用for循环检测写入的数据大小是否等于buf长度 |
132 | | - // 如果不等于就继续写入 |
133 | | - // 这是因为 TCP 是一个面向流的协议 |
134 | | - // 它并不保证一次 write 调用能够发送所有的数据 |
135 | | - // 作为示例,我们不检查是否全部写入 |
136 | | - _ = try connection.stream.write(buf[0..len]); |
137 | | - } |
138 | | - } |
139 | | - } |
140 | | - // 检查是否是 POLLNVAL | POLLERR | POLLHUP 事件,即是否有错误发生,或者连接断开 |
141 | | - else if ((sockfd.revents & |
142 | | - (context.POLLNVAL | context.POLLERR | context.POLLHUP)) != 0) |
143 | | - { |
144 | | - // 将 pollfd 和 connection 置为无效 |
145 | | - sockfds[i].fd = context.INVALID_SOCKET; |
146 | | - connections[i] = null; |
147 | | - std.log.info("client {} close", .{i}); |
| 55 | + if (data.len == 0) { |
| 56 | + std.log.info("client disconnected", .{}); |
| 57 | + break; |
148 | 58 | } |
149 | | - } |
150 | | - // #endregion exist-connections |
151 | 59 |
|
152 | | - // #region new-connection |
153 | | - // 检查是否有新的连接 |
154 | | - // 这里的 sockfds[0] 是 server 的 pollfd |
155 | | - // 这里的 nums 检查可有可无,因为我们只关心是否有新的连接,POLLIN 就足够了 |
156 | | - if (sockfds[0].revents & context.POLLIN != 0 and nums > 0) { |
157 | | - std.log.info("new client", .{}); |
158 | | - // 如果有新的连接,那么调用 accept |
159 | | - const client = try server.accept(); |
160 | | - for (1..max_sockets) |i| { |
161 | | - // 找到一个空的 pollfd,将新的连接放进去 |
162 | | - if (sockfds[i].fd == context.INVALID_SOCKET) { |
163 | | - sockfds[i].fd = client.stream.handle; |
164 | | - connections[i] = client; |
165 | | - std.log.info("new client {} comes", .{i}); |
166 | | - break; |
167 | | - } |
168 | | - // 如果没有找到空的 pollfd,那么说明连接数已经达到了最大值 |
169 | | - if (i == max_sockets - 1) { |
170 | | - @panic("too many clients"); |
| 60 | + // 消费已读取的数据 |
| 61 | + reader.interface.toss(data.len); |
| 62 | + |
| 63 | + // 将数据写回给客户端(echo) |
| 64 | + writer.interface.writeAll(data) catch |err| { |
| 65 | + std.log.err("write error: {}", .{err}); |
| 66 | + if (writer.err) |write_err| { |
| 67 | + std.log.err("underlying error: {}", .{write_err}); |
171 | 68 | } |
172 | | - } |
| 69 | + break; |
| 70 | + }; |
| 71 | + writer.interface.flush() catch |err| { |
| 72 | + std.log.err("flush error: {}", .{err}); |
| 73 | + break; |
| 74 | + }; |
173 | 75 | } |
174 | | - // #endregion new-connection |
175 | | - } |
176 | 76 |
|
177 | | - if (builtin.os.tag == .windows) { |
178 | | - try windows.ws2_32.WSACleanup(); |
| 77 | + stream.close(io); |
| 78 | + // #endregion exist-connections |
179 | 79 | } |
180 | 80 | } |
0 commit comments