单线程Reactor模型
Reactor模型只是对select\poll\epoll等网络模型的封装,本文讲解基于epoll实现Reactor模型
Reactor模型
单线程Reactor模型较为简单,如图:
服务器接收多个client连接请求后,统一交由Reactor处理,其中,新连接请求与数据交互分开处理:
当服务器到达一个新连接后 => 交给Acceptor处理,调用accept()取出连接文件描述符connfd =>为这个connfd绑定回调函数,加入Handler => Handler将connfd及其回调函数加入epoll => epoll检测到这个connfd有事件发生时,调用其回调函数
设计实现
Reactor主要由两部分组成
- fd和其绑定的回调函数
- 监听fd,调用其对应的回调函数
其实epoll中,data.ptr本身就可以指向一个callback,在这种情况下,就可以视为一种reactor模式了;但是对于select和poll,本身不能进行fd与callback的绑定,需要在用户态记录fd和callback的映射关系
由于本文的重点是Reactor模型,而且记录fd和callback的映射关系有很多的方便之处(如fd读写事件的切换,底层网络模型的更换等),其实现设计图如下:
Reactor组成:
- evblk:记录fd和回调函数的映射
- 事件数组:长度1024,索引为fd,值为ntyevent
- 块链表:当fd数量较多时,就需要新申请事件数组和块链表节点,挂到块链表上
- 由于进程内fd顺序增长,所以块链表节点采用尾插法(块链表也可以换成数组或deque)
- epfd:创建一个epoll,监听事件
- 将evblk中的数组元素加入epoll
API
- 回调函数
- recv_cb():fd指定可读事件时,绑定到connfd
- send_cb():fd指定可写事件时,绑定到connfd
- accept_cb():fd指定可读事件时,绑定到listenfd(全连接队列非空)
- reactor
- ntyreactor_init():创建epoll,reactor结构体初始化
- ntyreactor_alloc():分配事件数组和对应的块节点,插入到evblk中
- ntyreactor_idx():evblk索引函数
- ntyreactor_destory():销毁reactor
- 事件
- nty_event_set():设置事件数组元素值,也就是为fd绑定回调函数
- nty_event_add():将事件加入epoll以被监听
- ntyreactor_addlistener():调用nty_event_set()和nty_event_add(),主要用于socket初始化后,为listenfd绑定accept_cb函数
- ntyreactor_run:对于就绪的事件,执行对应的回调函数
代码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#define BUFFER_LENGTH 4096
#define MAX_EPOLL_EVENTS 1024
#define SERVER_PORT 8888
#define PORT_COUNT 100
typedef int NCALLBACK(int ,int, void*);
struct ntyevent {
int fd;
int events; //对应的监听事件,EPOLLIN和EPOLLOUT(不同的事件,走不同的回调函数)
void *arg; // reactor指针
int (*callback)(int fd, int events, void *arg);
int status; // epoll是否监听
char buffer[BUFFER_LENGTH]; // 读写buff也可分别设置
int length; // 实际从buff读取写入的数据长度
long last_active;
};
struct eventblock { // 块节点
struct eventblock *next;
struct ntyevent *events;
};
struct ntyreactor {
int epfd;
int blkcnt; // 块节点的数量
struct eventblock *evblk; // 存100w个连接 数组(fd定死了),deque等,这里采用链表
};
int recv_cb(int fd, int events, void *arg);
int send_cb(int fd, int events, void *arg);
struct ntyevent *ntyreactor_idx(struct ntyreactor *reactor, int sockfd);
// 设置reactor中的ntyevent节点
void nty_event_set(struct ntyevent *ev, int fd, NCALLBACK callback, void *arg) {
ev->fd = fd;
ev->callback = callback;
ev->events = 0;
ev->arg = arg;
ev->last_active = time(NULL);
return ;
}
// ntyevent节点加入reactor后,还需加入epoll监听
int nty_event_add(int epfd, int events, struct ntyevent *ev) {
struct epoll_event ep_ev = {0, {0}};
ep_ev.data.ptr = ev;
ep_ev.events = ev->events = events;
int op;
if (ev->status == 1) {
op = EPOLL_CTL_MOD;
} else {
op = EPOLL_CTL_ADD;
ev->status = 1;
}
if (epoll_ctl(epfd, op, ev->fd, &ep_ev) < 0) {
printf("event add failed [fd=%d], events[%d]\n", ev->fd, events);
return -1;
}
return 0;
}
// 从epoll中删除该fd,不再监听
int nty_event_del(int epfd, struct ntyevent *ev) {
struct epoll_event ep_ev = {0, {0}};
if (ev->status != 1) {
return -1;
}
ep_ev.data.ptr = ev;
ev->status = 0;
epoll_ctl(epfd, EPOLL_CTL_DEL, ev->fd, &ep_ev);
return 0;
}
// fd从监听读事件,变成监听写事件
int recv_cb(int fd, int events, void *arg) {
struct ntyreactor *reactor = (struct ntyreactor*)arg;
struct ntyevent *ev = ntyreactor_idx(reactor, fd);
int len = recv(fd, ev->buffer, BUFFER_LENGTH , 0); // 读读缓冲区
nty_event_del(reactor->epfd, ev); // 将该fd从epoll中删除,该fd需改成写事件加入epoll
if (len > 0) {
ev->length = len;
ev->buffer[len] = '\0';
printf("C[%d]:%s\n", fd, ev->buffer);
nty_event_set(ev, fd, send_cb, reactor);
nty_event_add(reactor->epfd, EPOLLOUT, ev);
} else if (len == 0) {
close(ev->fd);
//printf("[fd=%d] pos[%ld], closed\n", fd, ev-reactor->events);
} else {
close(ev->fd);
printf("recv[fd=%d] error[%d]:%s\n", fd, errno, strerror(errno));
}
return len;
}
// fd从监听写事件,变成监听读事件
int send_cb(int fd, int events, void *arg) {
struct ntyreactor *reactor = (struct ntyreactor*)arg;
struct ntyevent *ev = ntyreactor_idx(reactor, fd);
int len = send(fd, ev->buffer, ev->length, 0);
if (len > 0) {
printf("send[fd=%d], [%d]%s\n", fd, len, ev->buffer);
nty_event_del(reactor->epfd, ev);
nty_event_set(ev, fd, recv_cb, reactor);
nty_event_add(reactor->epfd, EPOLLIN, ev);
} else {
close(ev->fd);
nty_event_del(reactor->epfd, ev);
printf("send[fd=%d] error %s\n", fd, strerror(errno));
}
return len;
}
// listenfd监听新连接加入epoll
int accept_cb(int fd, int events, void *arg) {
struct ntyreactor *reactor = (struct ntyreactor*)arg;
if (reactor == NULL) return -1;
struct sockaddr_in client_addr;
socklen_t len = sizeof(client_addr);
int clientfd;
if ((clientfd = accept(fd, (struct sockaddr*)&client_addr, &len)) == -1) {
if (errno != EAGAIN && errno != EINTR) {
}
printf("accept: %s\n", strerror(errno));
return -1;
}
int flag = 0;
if ((flag = fcntl(clientfd, F_SETFL, O_NONBLOCK)) < 0) {
printf("%s: fcntl nonblocking failed, %d\n", __func__, MAX_EPOLL_EVENTS);
return -1;
}
struct ntyevent *event = ntyreactor_idx(reactor, clientfd);
nty_event_set(event, clientfd, recv_cb, reactor);
nty_event_add(reactor->epfd, EPOLLIN, event);
printf("new connect [%s:%d], pos[%d]\n",
inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), clientfd);
return 0;
}
// 初始化socket连接
int init_sock(short port) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
fcntl(fd, F_SETFL, O_NONBLOCK);
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
bind(fd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (listen(fd, 20) < 0) { // 20:Linux中全连接队列中连接的数量
printf("listen failed : %s\n", strerror(errno));
}
return fd;
}
// 分配一个块节点和数组,尾插到reactor中
int ntyreactor_alloc(struct ntyreactor *reactor) {
if (reactor == NULL) return -1;
if (reactor->evblk == NULL) return -1;
// 尾插,fd在进程内是顺序的
struct eventblock *blk = reactor->evblk;
while (blk->next != NULL) {
blk = blk->next;
}
// 先分配数组,因为内存越大,越容易分配失败
struct ntyevent *evs = (struct ntyevent*)malloc((MAX_EPOLL_EVENTS) * sizeof(struct ntyevent));
if (evs == NULL) {
printf("ntyreactor_alloc ntyevents failed\n");
return -2;
}
memset(evs, 0, (MAX_EPOLL_EVENTS) * sizeof(struct ntyevent));
// 分配节点
struct eventblock *block = (struct eventblock *)malloc(sizeof(struct eventblock));
if (block == NULL) {
printf("ntyreactor_alloc eventblock failed\n");
return -2;
}
memset(block, 0, sizeof(struct eventblock));
// 加入reactor
block->events = evs;
block->next = NULL;
blk->next = block;
reactor->blkcnt ++;
return 0;
}
// 索引函数,返回fd对应的event
struct ntyevent *ntyreactor_idx(struct ntyreactor *reactor, int sockfd) {
int blkidx = sockfd / MAX_EPOLL_EVENTS;
// 防止索引越界
// 其实小索引也可能越界:比如我第二个数组中的fd全部处理完了,那就该释放了(这里没释放),再来一个1024就找不到对应的事件了
while (blkidx >= reactor->blkcnt) {
ntyreactor_alloc(reactor);
}
int i = 0;
struct eventblock *blk = reactor->evblk;
while(i ++ < blkidx && blk != NULL) {
blk = blk->next;
}
return &blk->events[sockfd % MAX_EPOLL_EVENTS];
}
// 初始化reactor结构体
int ntyreactor_init(struct ntyreactor *reactor) {
if (reactor == NULL) return -1; // reactor内存清零
memset(reactor, 0, sizeof(struct ntyreactor));
reactor->epfd = epoll_create(1); // epoll初始化
if (reactor->epfd <= 0) {
printf("create epfd in %s err %s\n", __func__, strerror(errno));
return -2;
}
// 数组初始化
struct ntyevent *evs = (struct ntyevent*)malloc((MAX_EPOLL_EVENTS) * sizeof(struct ntyevent));
if (evs == NULL) {
printf("ntyreactor_alloc ntyevents failed\n");
return -2;
}
memset(evs, 0, (MAX_EPOLL_EVENTS) * sizeof(struct ntyevent));
// 块节点初始化
struct eventblock *block = (struct eventblock *)malloc(sizeof(struct eventblock));
if (block == NULL) {
printf("ntyreactor_alloc eventblock failed\n");
return -2;
}
memset(block, 0, sizeof(struct eventblock));
block->events = evs;
block->next = NULL;
reactor->evblk = block;
reactor->blkcnt = 1;
return 0;
}
// 销毁reactor
int ntyreactor_destory(struct ntyreactor *reactor) {
close(reactor->epfd); // 关闭epoll
struct eventblock *blk = reactor->evblk;
struct eventblock *blk_next = NULL;
// 链表的释放
while (blk != NULL) {
blk_next = blk->next;
free(blk->events);
free(blk);
blk = blk_next;
}
return 0;
}
// 将事件加入到reactor和epoll
int ntyreactor_addlistener(struct ntyreactor *reactor, int sockfd, NCALLBACK *acceptor) {
if (reactor == NULL) return -1;
if (reactor->evblk == NULL) return -1;
struct ntyevent *event = ntyreactor_idx(reactor, sockfd);
nty_event_set(event, sockfd, acceptor, reactor);
nty_event_add(reactor->epfd, EPOLLIN, event);
return 0;
}
// 启动reactor,reactor能支持百万连接,是因为epoll本身就能支持百万连接
int ntyreactor_run(struct ntyreactor *reactor) {
if (reactor == NULL) return -1;
if (reactor->epfd < 0) return -1;
if (reactor->evblk == NULL) return -1;
// 就绪列表中事件的data就有这个回调函数啊
// 而且下面也是直接取的data中的回调,为啥还要reactor?
struct epoll_event events[MAX_EPOLL_EVENTS+1]; // 就绪队列里的事件不需要取太多,多取几次就好
int checkpos = 0, i;
while (1) {
int nready = epoll_wait(reactor->epfd, events, MAX_EPOLL_EVENTS, 1000);
if (nready < 0) {
printf("epoll_wait error, exit\n");
continue;
}
for (i = 0;i < nready;i ++) {
// 不需要判断事件类型,直接调回调就行
struct ntyevent *ev = (struct ntyevent*)events[i].data.ptr;
ev->callback(ev->fd, events[i].events, ev->arg);
}
}
}
// 3, 6w, 1, 100 ==
// <remoteip, remoteport, localip, localport>
int main(int argc, char *argv[]) {
unsigned short port = SERVER_PORT; // listen 8888
if (argc == 2) {
port = atoi(argv[1]);
}
struct ntyreactor *reactor = (struct ntyreactor*)malloc(sizeof(struct ntyreactor));
ntyreactor_init(reactor);
int i = 0;
int sockfds[PORT_COUNT] = {0};
for (i = 0;i < PORT_COUNT;i ++) { // 一个连接是5元组,服务器多开些端口才能达到百万连接
sockfds[i] = init_sock(port+i); // 8888到8988都在监听连接,也就是一个进程有100个listenfd
ntyreactor_addlistener(reactor, sockfds[i], accept_cb);
}
ntyreactor_run(reactor);
ntyreactor_destory(reactor);
for (i = 0;i < PORT_COUNT;i ++) {
close(sockfds[i]);
}
free(reactor);
return 0;
}
tips
- 边缘触发ET/水平触发FT:
- 场景:客户向服务器socket读缓冲区一次发送32byte,但服务器一次只读10byte
- 边缘触发:一次事件只触发一次,也就是32bytes这次只读了10byte(只读一次),下次客户再发32byet,也只会从上次剩下的22bytes读10byte;
- 水平触发:一次事件会触发多次,只要fd可读或可写,会不断触发(加入到就绪队列),也就是一次事件会触发4次,32byte读取完。
- 边缘触发:适用于小数据的处理(尽量一次可读完或写完buff的)
- 水平触发:适用于大数据库处理(如读缓冲可能会装不下用户数据),listenfd(多次调用accept()把连接取出来,加快程序处理速度,也防止连接太多,连接队列装不下而丢失fd)。
- listen(fd,20):
- 在进行三次握手时,客户端第一次握手,该fd会加入Linux半连接队列,第三次握手时,该fd会加入全连接队列(也就是accept队列)
- 其中,20是listen允许连接的最大数量,但是在有些操作系统中,如苹果,这个20是半连接+全连接的数量,而Linux中,是全连接的数量
DDOS攻击
:进行大量的第一次握手,导致浪费了很多fd,而单个进程创建fd是有数量限制的(limit -a查看),当达到最大限制时,就导致Linux无法再接收正常请求了
- socket套接字:
- 一个ip+端口就是一个socket套接字,一个服务端socket+客户端socket就是一个连接
- 所以一台主机中的一个进程可以初始化很多套接字(监听更多的port就是了),在服务端,listenfd由socketfd转换而来。参考链接
- linux中一切皆fd,一切fd都有inode