C语言实现基于Linux,epoll和多线程的WebServer服务器
创始人
2024-11-04 03:08:44
0

代码结构:

在这里插入图片描述

Server.h

头文件,对函数进行了声明

#pragma once #include // 新建一个用于TCP监听的socket文件描述符,并返回 int initListenFd(unsigned short port);  // 启动epoll int epollRun(int lfd);  // accept建立连接 void* acceptClient(void* arg);  // 接收http请求, cfd表示连接socket, epfd表示epoll树 void* recvHttpRequest(void* arg);  // 解析HTTP的请求行 int parseRequestLine(const char *line, int cfd);  // 发送文件(即HTTP相应报文的数据部分,不包括状态行和首部行) int sendFile(const char* fileName, int cfd);  // 发送响应头(状态行+首部行) int sendHeadMsg(int cfd, int status, const char* descr, const char* type, int length);  // 根据文件的后缀/文件名,得到文件的type,作为HTTP响应报文的首部字段content_type的值 const char* getFileType(const char* name);  //发送目录 int sendDir(const char* dirName, int cfd);  // 将字符转换为整形 int hexToDec(char c);  //解码 // to 存储解码之后的数据, 传出参数, from被解码的数据, 传入参数 void decodeMsg(char* to, char* from); 

Server.c

函数实现

#include "Server.h" #include  #include  #include  #include  #include   // 设置socket非阻塞 #include   // 判断errno #include  #include  #include  #include  #include  #include  #include  #include  #include  #include    // 封装线程工作函数的参数 typedef struct FdInfo{     int fd; // 文件描述符(用于监听/通信)     int epfd; // epoll树实例      pthread_t tid; // 线程id  }FdInfo;  // 新建一个用于TCP监听的socket文件描述符,并返回 int initListenFd(unsigned short port){     // 1. 创建监听的fd     int lfd = socket(AF_INET, SOCK_STREAM, 0);     if(lfd==-1){         perror("socket");         return -1;     }     // 2. 设置端口复用     int opt = -1;     int ret = setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt);          if(ret == -1){         perror("setsockopt");         return -1;     }     // 3. 绑定Ip和端口号     struct sockaddr_in addr;     addr.sin_family = AF_INET;     addr.sin_port = htons(port);     addr.sin_addr.s_addr = INADDR_ANY;     ret = bind(lfd, (struct sockaddr*)&addr, sizeof addr);     if(ret == -1){         perror("bind");         return -1;     }         // 4. 设置监听     ret = listen(lfd, 128);     if(ret == -1){         perror("listen");         return -1;     }      // 5. 返回fd     return lfd; }   // 启动epoll int epollRun(int lfd){     // 1. 创建epoll实例     int epfd = epoll_create(1); // 该参数已经费用,1没有实际意义     if(epfd == -1){         perror("epoll_create");         return -1;     }      // 2. 将lfd添加到epoll的红黑树上      struct epoll_event ev; // 创建返回时的数据ev      ev.data.fd=lfd;      ev.events = EPOLLIN;      int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, lfd, &ev);      if(ret == -1){         perror("epoll_ctl(EPOLL_CTL_ADD)");         return -1;      }       // 3. 开始检测epoll树上是否有就绪的节点,并进行处理      struct epoll_event evs[1024];  //epoll_wait的传出参数,就绪的节点被放在里面      int size = sizeof(evs) / sizeof(struct epoll_event);        while(1){         int num = epoll_wait(epfd, evs, size, -1); //-1表示一直阻塞,直到检测到已就绪的文件描述符         for(int i=0;i  //遍历前num个就绪的节点              FdInfo *info = (FdInfo *)malloc(sizeof(FdInfo));                     int fd = evs[i].data.fd;             info->epfd = epfd;             info->fd = fd;             if(fd == lfd){                  // 如果是监听socket,则建立新的连接 accept                 // acceptClient(fd, epfd);                  pthread_create(&info->tid, NULL, acceptClient, info);             }             else{ // 如果是连接socket,则进行处理                 // recvHttpRequest(fd, epfd);                  pthread_create(&info->tid, NULL, recvHttpRequest, info);             }         }      } }  // accept建立连接,并将得到的用于连接的socket文件描述符添加到epoll树实例上去 void* acceptClient(void* arg){ // lfd表示用于监听的socket,epfd表示epoll实例      FdInfo *info = (FdInfo*)arg;     // 1. 建立连接     int cfd = accept(info->fd, NULL, NULL);     if(cfd == -1){         perror("accept");         return NULL;     }     // printf("连接socket:%d\n",cfd);      //2. 设置连接socket非阻塞     int flag = fcntl(cfd, F_GETFL);     flag |= O_NONBLOCK;     fcntl(cfd, F_SETFL, flag);      //3. 将用于连接的socket添加到epoll树上     struct epoll_event ev;     ev.data.fd=cfd ;     ev.events = EPOLLIN | EPOLLET ;  // 用于连接的socket即需要读,又需要写     int ret = epoll_ctl(info->epfd, EPOLL_CTL_ADD, cfd, &ev);     if(ret == -1){         perror("epoll_ctl(EPOLL_CTL_ADD)");         return NULL;     }     free(info);     return NULL; }  // 连接socket的工作函数 void* recvHttpRequest(void* arg){     FdInfo *info = (FdInfo*)arg;     int len = 0, total=0; // len是每一次while读取的数据长度,total表示总共的长度     char tmp[1024] = { 0 };  // 每一次循环读取的数据     char buf[4096] = { 0 }; // 存储整个的客户端数据块,即将每一次循环读取的数据连在一起     // 由于使用了非阻塞cfd,所以需要循环的接受数据     while((len=recv(info->fd, tmp, sizeof tmp, 0)) > 0){         if(total+len             memcpy(buf+total,tmp, len); //将mid_buf拼接到buf后面         }         total+=len;  // 更新total              }     // 判断recv是读完了数据,还是读数据失败了,因为二者都会返回-1(根据error number进行判断)     if(len==-1 && errno == EAGAIN){  //如果是读数据读完了,则可以得到一个HTTP请求报文         // 截取出HTTP的请求行         char *pt = strstr(buf, "\r\n"); //pt指针指向\r这个字符         int reqLen = pt-buf;         buf[reqLen] = '\0'; //直接截断         parseRequestLine(buf, info->fd);     }     else if (len == 0 ){ // 客户端断开了连接         epoll_ctl(info->epfd, EPOLL_CTL_DEL, info->fd, NULL); //从epoll模型上删除当前用于通信的节点         close(info->fd); //关闭文件描述符     }     else{ // 如果是读数据失败了         perror("recv");     }     free(info);     return NULL; }   // HTTP报文格式: // 方法 URL 版本[CRLF]  如:get /xxx/1.jpg HTTP/1.1 // 首部字段: 值[CRLF] // ...[CRLF] // 首部字段: 值[CRLF] // [CRLF] // 数据实体  // 解析HTTP的请求行 int parseRequestLine(const char *line, int cfd){      // 解析请求行     char method[12]; // 存储客户端请求方法,如GET/POST     char path[1024];     sscanf(line, "%[^ ] %[^ ]", method, path);      printf("请求内容: \nmethod:%s, path:%s\n\n",method, path);      // 不区分大小写的比较,如果不等于0,则返回-1(目前只接收get方法)     if(strcasecmp(method, "get") != 0){          return -1;     }     decodeMsg(path, path); //转换为utf8编码,这样可以支持中文等特殊字符      // 处理客户端请求的静态资源(目录或文件),因为当前获得的/xxx/1.jpg是相对于工作路径的,所以需要转换为./xxx/1.jpg或者xxx/1.jpg     char *file = NULL;     if(strcmp(path, "/") == 0){ //如果get当前的工作目录         file = "./";     }     else{         file = path+1; // get工作目录中的一个资源     }      // 判断文件的属性(目录还是文件)     struct stat st; //stat函数的传出采纳数     int ret = stat(file, &st);     if(ret == -1){ //-1表示文件不存在         // 如果文件不存在,返回404界面         sendHeadMsg(cfd, 404, "Not Found", getFileType(".html"), -1); //发送HTTP相应报文的状态行和首部行,-1表示让浏览器自己读数据的长度         sendFile("404.html", cfd);         return 0;     }      // 判断文件的类型,如果是目录     if(S_ISDIR(st.st_mode)) //S_ISDIR是Linux提供的宏,判断是否是目录,是则返回1     {         // 将本地目录的内容发送给客户端         sendHeadMsg(cfd, 200, "OK", getFileType(".html"), -1);         sendDir(file, cfd);     }     // 如果是文件     else{         // 将文件的内容发送给客户端         sendHeadMsg(cfd, 200, "OK", getFileType(file), st.st_size); //发送HTTP相应报文的状态行和首部行         sendFile(file, cfd);  //发送文件     }     return 0; }  // 发送响应头(状态行+首部行) int sendHeadMsg(int cfd, int status, const char* descr, const char* type, int length){      char buf[4096] = {0};     // 状态行     sprintf(buf, "http/1.1 %d %s\r\n", status, descr);     // 首部行和空行(\r\n)     sprintf(buf+strlen(buf), "content-type: %s\r\n", type);     sprintf(buf+strlen(buf), "content-length: %d\r\n\r\n", length);      //发送状态行和首部行     send(cfd, buf, strlen(buf), 0);      return 0; }  // 发送数文件(HTTP相应报文的数据部分),由于使用了TCP面向连接的流式传输协议,所以可以读一部分发一部分数据 int sendFile(const char* fileName, int cfd){  // cfd表示建立连接的socket文件描述符     // 1.打开文件,并获得文件描述符     int fd = open(fileName, O_RDONLY); //O_RDONLY表示只读文件     assert(fd>0); #if 0       // 直接手写发送数据,但是可以有更简单的方式     while(1){         char buf[1024];         int len = read(fd, buf, sizeof(buf)); //读数据          if(len>0){             send(cfd, buf, len, 0);  // 将读到的数据发送给客户端             usleep(10); // 给接收端一些时间去接收数据,防止客户端接收数据出错         }         else if(len == 0){             break;         }         else{             perror("read");         }     } #else      //直接使用系统函数sendfile发送文件,相比于手写更简单      off_t offset = 0;     int size = lseek(fd, 0, SEEK_END); //得到文件的大小,seek_end将文件指针移动到文件的末尾     lseek(fd, 0, SEEK_SET); // seek_set将文件的指针重新移动到文件的头部     while(offset         int ret = sendfile(cfd, fd, &offset, size-offset); //sendfile会自动给offset赋值,表示当前读的偏移量         // printf("ret value: %d\n", ret);         if(ret == -1 && errno!=EAGAIN){             perror("sendfile");         }     }          #endif     close(fd);     return 0; }  /* HTML文件发送目录时的格式               test                        // 每一都tr都是一个行,td是一个列                   // 文件名                    // 文件大小             
*/ //发送目录,使用scandir进行单层目录的遍历 int sendDir(const char* dirName, int cfd){ //dirName表示目录名 char buf[4096] = { 0 }; sprintf(buf, "%s", dirName); struct dirent** namelist; //namelist指向的是一个指针数组struct dirent* tmp[] int num = scandir(dirName, &namelist, NULL, alphasort); for(int i=0;i char* name = namelist[i]->d_name; //拿到了文件名字 struct stat st; //将目录名与文件名进行拼接 char subPath[1024] = { 0 }; sprintf(subPath, "%s/%s", dirName, name); stat(subPath, &st); //用于判断name所表示的文件的类型 if(S_ISDIR(st.st_mode)){ //如果是目录 sprintf(buf+strlen(buf), "", name, name, st.st_size); //使用a标签设置超链接标签 } else{ // 如果是文件 sprintf(buf+strlen(buf), "", name, name, st.st_size); //使用a标签设置超链接标签 } send(cfd, buf, strlen(buf),0); memset(buf,0,sizeof buf); free(namelist[i]); } sprintf(buf, "
%s%ld
%s%ld
"); send(cfd, buf, strlen(buf), 0); free(namelist); return 0; } // 根据文件的后缀/文件名,得到文件的type,作为HTTP响应报文的首部字段content_type的值 const char* getFileType(const char* name) { // a.jpg a.mp4 a.html // 自右向左查找‘.’字符, 如不存在返回NULL const char* dot = strrchr(name, '.'); if (dot == NULL) return "text/plain; charset=utf-8"; // 纯文本 if (strcmp(dot, ".html") == 0 || strcmp(dot, ".htm") == 0) return "text/html; charset=utf-8"; if (strcmp(dot, ".jpg") == 0 || strcmp(dot, ".jpeg") == 0) return "image/jpeg"; if (strcmp(dot, ".gif") == 0) return "image/gif"; if (strcmp(dot, ".png") == 0) return "image/png"; if (strcmp(dot, ".css") == 0) return "text/css"; if (strcmp(dot, ".au") == 0) return "audio/basic"; if (strcmp(dot, ".wav") == 0) return "audio/wav"; if (strcmp(dot, ".avi") == 0) return "video/x-msvideo"; if (strcmp(dot, ".mov") == 0 || strcmp(dot, ".qt") == 0) return "video/quicktime"; if (strcmp(dot, ".mpeg") == 0 || strcmp(dot, ".mpe") == 0) return "video/mpeg"; if (strcmp(dot, ".vrml") == 0 || strcmp(dot, ".wrl") == 0) return "model/vrml"; if (strcmp(dot, ".midi") == 0 || strcmp(dot, ".mid") == 0) return "audio/midi"; if (strcmp(dot, ".mp3") == 0) return "audio/mpeg"; if (strcmp(dot, ".ogg") == 0) return "application/ogg"; if (strcmp(dot, ".pac") == 0) return "application/x-ns-proxy-autoconfig"; return "text/plain; charset=utf-8"; } // 将字符转换为整形数 int hexToDec(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return 0; } // 解码 // to 存储解码之后的数据, 传出参数, from被解码的数据, 传入参数 void decodeMsg(char* to, char* from) { for (; *from != '\0'; ++to, ++from) { // isxdigit -> 判断字符是不是16进制格式, 取值在 0-f // Linux%E5%86%85%E6%A0%B8.jpg if (from[0] == '%' && isxdigit(from[1]) && isxdigit(from[2])) { // 将16进制的数 -> 十进制 将这个数值赋值给了字符 int -> char // B2 == 178 // 将3个字符, 变成了一个字符, 这个字符就是原始数据 *to = hexToDec(from[1]) * 16 + hexToDec(from[2]); // 跳过 from[1] 和 from[2] 因此在当前循环中已经处理过了 from += 2; } else { // 字符拷贝, 赋值 *to = *from; } } *to = '\0'; }

main函数

#include "Server.h" #include  #include  #include  int main(int argc, char* argv[]){      // 用户传入的参数为 [默认参数,port, path],即启动当前服务器,设置端口号port和工作路目录path     if(argc<3){         printf("./a.out port path\n");         return -1;     }      // 拿到端口号     unsigned short port = atoi(argv[1]);  // argv to int      // 修改当前目录到工作目录     chdir(argv[2]);      printf("端口号: %d\n工作目录: %s\n", port, argv[2]);       // 初始化用于监听的套接字     int lfd = initListenFd(port); //设置端口号,并返回一个监听文件描述符      printf("用于监听的文件描述符: %d\n",lfd);      //启动服务器程序     epollRun(lfd);          return 0; } 

启动指令:

# 1. 在文件目录下,编译所有.c文件,生成可执行文件Server gcc *.c -l pthread -o Server  # 2. 运行Server, 运行指令的格式为 ./Server port filePath, 如: ./Server 10000 / # 表示端口号为10000, 工作目录为根目录/(只是实例,一般需要自己的一个sources资源目录) 

控制台输打印示例在这里插入图片描述

参考:大丙课堂

相关内容

热门资讯

终于发现!微信拼三张房间卡在哪... 微信游戏中心:拼三张房卡,添加微信【56001354】,进入游戏中心或相关小程序,搜索“微信拼三张房...
终于发现!微信里面炸金花房卡哪... 微信游戏中心:炸金花房卡,添加微信【66336574】,进入游戏中心或相关小程序,搜索“微信炸金花房...
终于发现!微信炸金花在哪里充值... 微信游戏中心:炸金花房卡,添加微信【71319951】,进入游戏中心或相关小程序,搜索“微信炸金花房...
终于发现!炸金花房卡链接去哪里... 微信游戏中心:炸金花房卡,添加微信【56001354】,进入游戏中心或相关小程序,搜索“微信炸金花房...
终于发现!微信牛牛房卡找谁买,... 微信游戏中心:牛牛房卡,添加微信【66336574】,进入游戏中心或相关小程序,搜索“微信牛牛房卡”...
终于发现!怎么创建拼三张房间卡... 微信游戏中心:拼三张房卡,添加微信【71319951】,进入游戏中心或相关小程序,搜索“微信拼三张房...
终于发现!炸金花房卡链接在哪买... 微信游戏中心:炸金花房卡,添加微信【56001354】,进入游戏中心或相关小程序,搜索“微信炸金花房...
终于发现!怎么创建牛牛房间房卡... 微信游戏中心:牛牛房卡,添加微信【66336574】,进入游戏中心或相关小程序,搜索“微信牛牛房卡”...
终于发现!创建斗牛链接房间房卡... 微信游戏中心:斗牛房卡,添加微信【71319951】,进入游戏中心或相关小程序,搜索“微信斗牛房卡”...
终于发现!微信玩炸金花房卡链接... 微信游戏中心:炸金花房卡,添加微信【56001354】,进入游戏中心或相关小程序,搜索“微信炸金花房...
终于发现!微信里面斗牛链接房卡... 微信游戏中心:斗牛房卡,添加微信【66336574】,进入游戏中心或相关小程序,搜索“微信斗牛房卡”...
终于发现!想找个拼三张房卡在哪... 微信游戏中心:拼三张房卡,添加微信【71319951】,进入游戏中心或相关小程序,搜索“微信拼三张房...
终于发现!我买炸金花房卡链接,... 微信游戏中心:炸金花房卡,添加微信【56001354】,进入游戏中心或相关小程序,搜索“微信炸金花房...
终于发现!微信拼三张购买房卡方... 微信游戏中心:拼三张房卡,添加微信【66336574】,进入游戏中心或相关小程序,搜索“微信拼三张房...
终于发现!微信拼三张购买房卡,... 微信游戏中心:拼三张房卡,添加微信【71319951】,进入游戏中心或相关小程序,搜索“微信拼三张房...
终于发现!微信玩斗牛怎么买房卡... 微信游戏中心:斗牛房卡,添加微信【56001354】,进入游戏中心或相关小程序,搜索“微信斗牛房卡”...
终于发现!斗牛链接房卡怎么搞,... 微信游戏中心:斗牛房卡,添加微信【66336574】,进入游戏中心或相关小程序,搜索“微信斗牛房卡”...
终于发现!微信群炸金花房卡到哪... 微信游戏中心:炸金花房卡,添加微信【71319951】,进入游戏中心或相关小程序,搜索“微信炸金花房...
终于发现!微信牛牛房卡链接在哪... 微信游戏中心:斗牛房卡,添加微信【56001354】,进入游戏中心或相关小程序,搜索“微信斗牛房卡”...
终于发现!想找个微信牛牛房卡在... 微信游戏中心:牛牛房卡,添加微信【66336574】,进入游戏中心或相关小程序,搜索“微信牛牛房卡”...