C++封装一个Epoll类,实现epoll简单使用

#include <iostream>
#include <vector>
#include <sys/epoll.h>
#include "tcpsocket.hpp"

class Epoll {
    private:
        int _epfd;
    public:
        bool Init() {
            //创建epoll
            
            //接口原型:int epoll_create(int size);
            _epfd = epoll_create(1);
            if (_epfd < 0) {
                perror("epoll create error");
                return false;
            }
            return true;
        }
        bool Add(TcpSocket sock, uint32_t events = 0) {
            sock.SetNonBlock();
            int fd = sock.GetSockFd();
            
            //定义事件
            struct epoll_event ev;
            ev.events = EPOLLIN | events;
            ev.data.fd = fd;
            
            //接口原型:epoll_ctl(int epfd,int op,int fd,struct epoll_event *event);
            int ret = epoll_ctl(_epfd, EPOLL_CTL_ADD, fd, &ev);
            if (ret < 0) {
                perror("epoll ctrl error");
                return false;
            }
            return true;
        }
        bool Del(TcpSocket sock) {
            int fd = sock.GetSockFd();
            int ret = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, NULL);
            if (ret < 0) {
                perror("epoll ctrl error");
                return false;
            }
            return true;
        }
        bool Wait(std::vector<TcpSocket> &list, int ms_timeout = 3000) {
            //接口原型:int epoll_wait(int epfd, struct epoll_event *events,
            //  int maxevents, int timeout);
            struct epoll_event evs[10];
            int nfds = epoll_wait(_epfd, evs, 10, ms_timeout);
            if (nfds < 0) {
                perror("epoll wait error");
                return false;
            }else if (nfds == 0) {
                std::cout << "epoll wait timeout\n";
                return false;
            }
            for (int i = 0; i < nfds; i++) {
                int fd = evs[i].data.fd;
                TcpSocket sock;
                sock.SetSockFd(fd);
                list.push_back(sock);
            }
            return true;
        }
};

int main(){
    TcpSocket lst_sock;			//listen socket:监听socket
    CHECK_RET(lst_sock.Socket());
    CHECK_RET(lst_sock.Bind("0.0.0.0", 9000));
    CHECK_RET(lst_sock.Listen());

    Epoll epoll;
    CHECK_RET(epoll.Init());
    CHECK_RET(epoll.Add(lst_sock, EPOLLET));
    while(1) {
        std::vector<TcpSocket> list;
        bool ret = epoll.Wait(list);
        if (ret == false) {
            continue;
        }
        for (int i = 0; i < list.size(); i++) {
            if (list[i].GetSockFd() == lst_sock.GetSockFd()) {
                TcpSocket cli_sock;
                lst_sock.Accept(cli_sock);
                epoll.Add(cli_sock, EPOLLET);
            }else {
                std::string buf;
                list[i].Recv(buf);
                std::cout << "client say: " << buf << std::endl;
            }
        }

    }
    lst_sock.Close();
    return 0;
}

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
好的,我可以回答这个问题。以下是一个使用 C 语言编写的 epoll 实例: ```c #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> #define MAX_EVENTS 10 #define PORT 808 int main() { int server_fd, new_socket, epoll_fd, n; struct sockaddr_in address; char buffer[1024] = {}; struct epoll_event event, events[MAX_EVENTS]; // 创建 socket if ((server_fd = socket(AF_INET, SOCK_STREAM, )) == ) { perror("socket failed"); exit(EXIT_FAILURE); } // 设置 socket 地址 address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); // 绑定 socket if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < ) { perror("bind failed"); exit(EXIT_FAILURE); } // 监听 socket if (listen(server_fd, 3) < ) { perror("listen failed"); exit(EXIT_FAILURE); } // 创建 epoll 实例 if ((epoll_fd = epoll_create1()) < ) { perror("epoll_create1 failed"); exit(EXIT_FAILURE); } // 添加监听事件 event.events = EPOLLIN; event.data.fd = server_fd; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_fd, &event) < ) { perror("epoll_ctl EPOLL_CTL_ADD failed"); exit(EXIT_FAILURE); } while (1) { // 等待事件 n = epoll_wait(epoll_fd, events, MAX_EVENTS, -1); if (n < ) { perror("epoll_wait failed"); exit(EXIT_FAILURE); } // 处理事件 for (int i = ; i < n; i++) { if (events[i].data.fd == server_fd) { // 处理新连接 if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&address)) < ) { perror("accept failed"); exit(EXIT_FAILURE); } // 添加新连接到 epoll 实例 event.events = EPOLLIN; event.data.fd = new_socket; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, new_socket, &event) < ) { perror("epoll_ctl EPOLL_CTL_ADD failed"); exit(EXIT_FAILURE); } printf("New connection, socket fd is %d, ip is : %s, port : %d\n", new_socket, inet_ntoa(address.sin_addr), ntohs(address.sin_port)); } else { // 处理已连接的 socket int socket_fd = events[i].data.fd; int valread = read(socket_fd, buffer, 1024); if (valread == ) { // 连接关闭 epoll_ctl(epoll_fd, EPOLL_CTL_DEL, socket_fd, NULL); close(socket_fd); printf("Connection closed, socket fd is %d\n", socket_fd); } else { // 处理数据 printf("Received message from socket fd %d: %s\n", socket_fd, buffer); write(socket_fd, buffer, strlen(buffer)); } } } } return ; } ``` 这个程序创建了一个 socket 并监听端口 808,使用 epoll 实现了异步事件处理。当有新连接时,将其添加到 epoll 实例中,并在有数据可读时处理数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

giturtle

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值