/*
 * 03_epoll_et_server.c —— epoll ET (边沿触发) 模式 echo 服务器
 *
 * 编译: gcc 03_epoll_et_server.c -o et_srv
 * 运行: ./et_srv 9002
 * 测试: yes "abc" | head -c 100000 | nc localhost 9002
 *
 * ET 模式三大铁律：
 *   1) socket 必须 O_NONBLOCK
 *   2) read/accept 必须循环到 EAGAIN
 *   3) 否则丢事件 / 卡死
 *
 * 跟 LT 版对比"epoll_wait 调用次数"，能直观看到 ET 节省 syscall。
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h>

#define MAX_EVENTS 64
#define BUF_SIZE   1024

static void set_nonblock(int fd) {
    int fl = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

static int make_listen_socket(int port) {
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    int yes = 1; setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
    set_nonblock(fd);    /* 监听 socket 也设非阻塞 */
    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0 || listen(fd, 64) < 0) {
        perror("bind/listen"); exit(1);
    }
    printf("🚀 epoll [ET] 服务器已启动，端口 %d\n", port);
    return fd;
}

int main(int argc, char *argv[]) {
    int port = (argc > 1) ? atoi(argv[1]) : 9002;
    int lfd = make_listen_socket(port);

    int epfd = epoll_create1(EPOLL_CLOEXEC);

    struct epoll_event ev = {.events = EPOLLIN | EPOLLET, .data.fd = lfd};
    epoll_ctl(epfd, EPOLL_CTL_ADD, lfd, &ev);

    struct epoll_event events[MAX_EVENTS];
    long wait_count = 0, total_bytes = 0;

    while (1) {
        int n = epoll_wait(epfd, events, MAX_EVENTS, -1);
        if (n < 0) { if (errno == EINTR) continue; perror("epoll_wait"); break; }
        wait_count++;
        printf("🔔 [ET] epoll_wait 第 %ld 次返回, 就绪 %d 个 fd, 累计接收 %ld 字节\n",
               wait_count, n, total_bytes);

        for (int i = 0; i < n; i++) {
            int fd = events[i].data.fd;
            uint32_t evs = events[i].events;

            if (fd == lfd) {
                /* ET 模式: 必须循环 accept 到 EAGAIN，否则会漏新连接 */
                while (1) {
                    struct sockaddr_in cli;
                    socklen_t cl = sizeof(cli);
                    int conn = accept(lfd, (struct sockaddr*)&cli, &cl);
                    if (conn < 0) {
                        if (errno == EAGAIN || errno == EWOULDBLOCK) break;
                        perror("accept"); break;
                    }
                    set_nonblock(conn);
                    ev.events  = EPOLLIN | EPOLLET | EPOLLRDHUP;
                    ev.data.fd = conn;
                    epoll_ctl(epfd, EPOLL_CTL_ADD, conn, &ev);
                    printf("    ➕ 新客户端 fd=%d, 来自 %s:%d\n",
                           conn, inet_ntoa(cli.sin_addr), ntohs(cli.sin_port));
                }
            } else {
                if (evs & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) {
                    printf("    🗑  fd=%d 关闭\n", fd);
                    close(fd);
                    continue;
                }
                if (evs & EPOLLIN) {
                    /* ET 模式: 必须循环 read 到 EAGAIN */
                    while (1) {
                        char buf[BUF_SIZE];
                        ssize_t r = read(fd, buf, sizeof(buf));
                        if (r > 0) {
                            total_bytes += r;
                            write(fd, buf, r);
                            continue;
                        }
                        if (r == 0) {
                            printf("    👋 fd=%d 对端关闭\n", fd);
                            close(fd);
                            break;
                        }
                        if (errno == EAGAIN || errno == EWOULDBLOCK) {
                            /* 数据读完了，正常退出循环 */
                            break;
                        }
                        perror("read"); close(fd); break;
                    }
                }
            }
        }
    }
    close(epfd);
    close(lfd);
    return 0;
}
