本次主要解决上次遗留的数据结构问题
代码部分
头文件
#ifndef STRUCT_H_ #define STRUCT_H_ #include <stdio.h> #define BUFFER_LENGTH 1024 #define EPOLL_LENGTH 1024 typedef struct conn_item conn_item_t; typedef struct conn_block conn_block_t; typedef struct reactor_node reactor_node_t; int reactor_init(reactor_node_t* reactor); void reactor_dest(reactor_node_t* reactor); int reactor_block_connect(reactor_node_t* reactor); int reactor_item_connect(reactor_node_t* reactor, int fd); #endif
源文件
#include "struct.h" #include <stdlib.h> #include <string.h> typedef struct conn_item { int fd; char wbuffer[BUFFER_LENGTH]; int wc; char rbuffer[BUFFER_LENGTH]; int rc; } conn_item_t; typedef struct conn_block { struct conn_item* conntions; struct conn_block* next; } conn_block_t; typedef struct reactor_node { int epfd; int blcnt; struct conn_block* block_heander; } reactor_node_t; int reactor_init(reactor_node_t* reactor) { if(!reactor) return -1; reactor->block_heander = malloc(sizeof(conn_block_t) + EPOLL_LENGTH * sizeof(conn_item_t)); if(reactor->block_heander == NULL) return -1; reactor->block_heander->next = NULL; reactor->block_heander->conntions = (conn_item_t*)(reactor->block_heander + 1); reactor->blcnt = 1; reactor->epfd = epoll_create(1); } void reactor_dest(reactor_node_t* reactor) { if(!reactor) return; if(!reactor->block_heander) free(reactor->block_heander); close(reactor->epfd); } int reactor_block_connect(reactor_node_t* reactor) { if(!reactor) return -1; conn_block_t* block = malloc(sizeof(conn_block_t) + EPOLL_LENGTH * sizeof(conn_item_t)); if(block == NULL) return -1; conn_block_t* temp = reactor->block_heander; while(temp->next != NULL) temp = temp->next; temp->next = block; block->conntions = (conn_item_t*)(block + 1); reactor->blcnt++; return 0; } int reactor_item_connect(reactor_node_t* reactor, int fd) { int i = 0; if(!reactor) return -1; int pos = fd / EPOLL_LENGTH; while(pos > reactor->blcnt) { reactor_block_connect(reactor); } conn_block_t* blk = reactor->block_heander; for(; i < pos; i++) { blk = blk->next; } int idx = fd % EPOLL_LENGTH; blk->conntions[pos].fd = fd; memset(blk->conntions[pos].rbuffer, 0, BUFFER_LENGTH); memset(blk->conntions[pos].wbuffer, 0, BUFFER_LENGTH); blk->conntions[pos].rc = 0; blk->conntions[pos].wc = 0; return 0; }
数据结构示意图
代码解读
上次我们是搞了一个很大的数组,这次我们做出一些优化。把做出一个链式结构,一个链表头,下面有很多块。块里面是conn_item,一个块里面有1024个conn_item。