IO多路复用通常用于处理单进程高并发,在Linux中,一切皆文件,一个socket连接会对应一个文件描述符,在监听多个文件描述符的状态应用中epoll相对于select和poll效率更高
epoll本质是系统在内核维护了一颗红黑树,监听的文件描述符会作为新的节点插入红黑树,epoll会等待有状态变化的节点记录在链表里,然后拷贝到用户所给的数组里面返回出来
以下是一个独立的服务端代码,可以补充业务代码进行具体使用
sever.h
//
// Created by YEZI on 2024/5/24.
//
#ifndef SEVER_H
#define SEVER_H
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sstream>
#define MAX_EVENTS 8
#define PORT 8888
#define BUFFER_SIZE 512
#define BACKLOG_SIZE 16 // 请求队列最大长度
class Sever {
private:
uint16_t port;
int server_fd = -1;
int epoll_fd = -1;
sockaddr_in server_addr{}, client_addr{};
socklen_t client_addr_len = sizeof(client_addr);
epoll_event event{}, events[MAX_EVENTS]{};
public:
explicit Sever(uint16_t port =