linux 内核2.4版本以上开始支持epoll, epoll相比select性能有较大的提升,首先支持的连接数基本不受限制,只受到内存等系统资源的限制,epoll是一种异步通知机制,只有有网络事件发生了,就会主动加入监听集合,select需要轮训事件集合,这样效率会低很多,尤其连接数多,但大部分连接不活跃的情况,select 的效率会低很多。目前大部分的linux网络库,底层都是epoll实现。下面只是一个最基本的epoll模型的实例
#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
class epoll_server
{
public:
epoll_server();
virtual ~epoll_server();
bool init(int port, int sock_count);
bool init(const char* ip, int port, int sock_count);
int epoll_server_wait(int time_out);
int accept_new_client();
int recv_data(int sock, char* recv_buf);
int send_data(int sock, char* send_buf, int buf_l