基于主从Reactor模型实现高并发服务器

打印 上一主题 下一主题

主题 925|帖子 925|积分 2775

1. 项目简介

1.1 环境先容


  • 服务器摆设:Linux-Centos – 2核2G的腾讯云服务器。
  • 项目用到的技术栈:C++、多线程、Epoll等。
1.2 项目定位


  • 主(从)Reactor模型服务器,主Reactor线程只负责监听形貌符,获取新建连接。这样就保证了新连接的获取比较高效,提高了服务器的并发性能。主Reactor获取到新连接后分发给子Reactor举行通讯变乱监控。
  • 子(从)Reactor线程监控各自文件形貌符下的读写变乱,举行数据读写以及业务处理。
  • One Thread One Loop的头脑就是把全部的操纵都放到线程中举行,一个线程对应一个EventLoop。
1.3 功能模块团体划分

项目实现目标:带有协议支持的Reactor模型高性能服务器。模块划分如下:

  • Server模块:实现Reactor模型的TCP服务器。


  • 协议模块:对于自主实现的Reactor模型服务器提供应用层协议支持,项目中支持的Http协议。

2. Reactor简介

2.1 Reactor模型分析

在高性能的I/O筹划中,Reactor模型用于同步I/O。
优点:

  • 响应快,不必为单个同步时间所壅闭(虽然Reactor本身依然是同步的);
  • 可以最大水平的避免复杂的多线程及同步标题,而且避免了多线程/进程的切换开销。

    • 可扩展性:可以方便地通过增加Reactor实例个数来充分利用CPU资源。
    • 可复用性,Reactor模型本身与详细变乱处理逻辑无关,具有很高的复用性。

  • Rector模型基于变乱驱动,特别得当处理海量的I/O。
2.2 多Reactor多线程分析:多I/O多路复用+线程池(业务处理)


  • 在主Reactor中处理新连接请求变乱,有新连接到来则分发到⼦Reactor中监控。
  • 在⼦Reactor中进⾏客⼾端通讯监控,有变乱触发,则接收数据分发给Worker线程池。
  • Worker线程池分配独⽴的线程进⾏详细的业务处理。⼯作线程处理完毕后,将响应交给⼦Reactor线程进⾏数据响应。
  • 优点:充分的利用了CPU多核资源,主从Reactor各自完成各自的任务。

3. 日记宏的编写

在实现各个模块之前先将日记实现方便打印找到步伐标题所在:
  1. #pragma once
  2. #include <iostream>
  3. #include <time.h>
  4. #include <stdarg.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>
  8. #include <unistd.h>
  9. #include <stdlib.h>
  10. #define SIZE 1024
  11. #define Info 0
  12. #define Debug 1
  13. #define Warning 2
  14. #define Error 3
  15. #define Fatal 4
  16. #define Screen 1
  17. #define Onefile 2
  18. #define Classfile 3
  19. #define LogFile "log.txt"
  20. class Log
  21. {
  22. public:
  23.     Log()
  24.     {
  25.         printMethod = Screen;
  26.         path = "./log/";
  27.     }
  28.     void Enable(int method)
  29.     {
  30.         printMethod = method;
  31.     }
  32.     std::string levelToString(int level)
  33.     {
  34.         switch (level)
  35.         {
  36.         case Info:
  37.             return "Info";
  38.         case Debug:
  39.             return "Debug";
  40.         case Warning:
  41.             return "Warning";
  42.         case Error:
  43.             return "Error";
  44.         case Fatal:
  45.             return "Fatal";
  46.         default:
  47.             return "None";
  48.         }
  49.     }
  50.    
  51.     void printLog(int level, const std::string &logtxt)
  52.     {
  53.         switch (printMethod)
  54.         {
  55.         case Screen:
  56.             std::cout << logtxt << std::endl;
  57.             break;
  58.         case Onefile:
  59.             printOneFile(LogFile, logtxt);
  60.             break;
  61.         case Classfile:
  62.             printClassFile(level, logtxt);
  63.             break;
  64.         default:
  65.             break;
  66.         }
  67.     }
  68.     void printOneFile(const std::string &logname, const std::string &logtxt)
  69.     {
  70.         std::string _logname = path + logname;
  71.         int fd = open(_logname.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666); // "log.txt"
  72.         if (fd < 0)
  73.             return;
  74.         write(fd, logtxt.c_str(), logtxt.size());
  75.         close(fd);
  76.     }
  77.     void printClassFile(int level, const std::string &logtxt)
  78.     {
  79.         std::string filename = LogFile;
  80.         filename += ".";
  81.         filename += levelToString(level); // "log.txt.Debug/Warning/Fatal"
  82.         printOneFile(filename, logtxt);
  83.     }
  84.     ~Log()
  85.     {
  86.     }
  87.     void operator()(int level, const char *format, ...)
  88.     {
  89.         time_t t = time(nullptr);
  90.         struct tm *ctime = localtime(&t);
  91.         char leftbuffer[SIZE];
  92.         snprintf(leftbuffer, sizeof(leftbuffer), "[%s][%d-%d-%d %d:%d:%d]", levelToString(level).c_str(),
  93.                  ctime->tm_year + 1900, ctime->tm_mon + 1, ctime->tm_mday,
  94.                  ctime->tm_hour, ctime->tm_min, ctime->tm_sec);
  95.         va_list s;
  96.         va_start(s, format);
  97.         char rightbuffer[SIZE];
  98.         vsnprintf(rightbuffer, sizeof(rightbuffer), format, s);
  99.         va_end(s);
  100.         // 格式:默认部分+自定义部分
  101.         char logtxt[SIZE * 2];
  102.         snprintf(logtxt, sizeof(logtxt), "%s %s", leftbuffer, rightbuffer);
  103.         // printf("%s", logtxt); // 暂时打印
  104.         printLog(level, logtxt);
  105.     }
  106. private:
  107.     int printMethod;
  108.     std::string path;
  109. };
  110. Log lg;
复制代码
4. Server模块

该模块主要实现TCP服务器,该模块包含了:Buffer模块、TimeQueue模块、Any模块、Socket模块、Acceptor模块、Poller模块、Channel模块、Connection模块、LoopThreadPool模块、EventLoop模块、TcpServer模块。
以下将上述模块的根本功能实现。
4.1 Buffer模块

4.1.1 Buffer的功能


4.1.2 Buffer的实现头脑

Buffer实现头脑如下:

  • 想要实现缓冲区首先要有一块内存空间,使用vector,vector的底层使用的就是一个线性的内存空间。
  • 一个读偏移记载当前读取数据的位置。一个写偏移记载当前的写入位置。
  • 写入数据:从写偏移的位置开始写入,如果后续空间足够直接写,反之就扩容:这里的扩容比较特殊,可以从团体空闲空间(当数据被读取,读偏移会向后移动,前面的空间是空闲的状态)和写偏移后的空闲空间两种情况考虑,如果团体空间足够,将现有数据移动到起始位置。如果不敷,扩容,从当前写位置开始扩容足够的大小。数据写入乐成后,写偏移记得向后偏移。


  • 读取数据:从当前读偏移开始读取,前提是有数据可读。可读数据的大小–写偏移和读偏移之间的数据。

4.1.3 Buffer的实现

(1)笔墨形貌Buffer类接口的详细筹划:

(2)Buffer类的筹划接口函数:
  1. #include <vector>
  2. #include <cstdint>
  3. #define BUFFER_DEFAULT_SIZE 1024    // Buffer 默认起始大小
  4. class Buffer
  5. {
  6. public:
  7.     Buffer()
  8.             :_reader_idx(0)
  9.             ,_writer_idx(0),
  10.             _buffer(BUFFER_DEFAULT_SIZE)
  11.     {}
  12.    
  13.     // 获取当前写入起始地址
  14.     void *WirtePosition();
  15.     // 获取当前读取起始地址
  16.     void *ReadPosition();
  17.     // 获取缓冲区末尾空闲空间大小--写偏移之后的空闲空间
  18.     uint64_t TailIdleSize();
  19.     // 获取缓冲区起始空闲空间大小--读偏移之前的空闲空间
  20.     uint64_t HeadIdleSize();
  21.     // 获取可读数据大小
  22.     uint16_t ReadAbleSize();
  23.     // 将读偏移向后移动
  24.     void MoveReadOffset(uint64_t len);
  25.     // 将写偏移向后移动
  26.     void MoveWriteOffset(uint64_t len);
  27.     // 确保可写空间足够(整体空闲空间够了就移动数据。否则就扩容)
  28.     void EnsureWriteSpace(uint64_t len);
  29.     // 写入数据
  30.     void Write(void *data, uint64_t len);
  31.     // 读取数据
  32.     void Read(void *buf, uint64_t len);
  33.     // 清空缓冲区
  34.     void Clear();
  35.    
  36. private:
  37.     std::vector<char> _buffer; // 使用vector进行内存空间管理
  38.     uint64_t _reader_idx;      // 读偏移
  39.     uint64_t _writer_idx;      // 写偏移
  40. };
复制代码
(3)Buffer类的接口函数实现:
  1. #pragma once
  2. #include <iostream>
  3. #include <vector>
  4. #include <string>
  5. #include <cassert>
  6. #include <cstring>
  7. using std::cout;
  8. using std::endl;
  9. #define BUFFER_DEFAULT_SIZE 1024
  10. class Buffer
  11. {
  12. private:
  13.     std::vector<char> _buffer;
  14.     uint64_t _read_index;
  15.     uint64_t _write_index;
  16. public:
  17.     Buffer()
  18.         :_read_index(0)
  19.         ,_write_index(0)
  20.         ,_buffer(BUFFER_DEFAULT_SIZE)
  21.     {}
  22.     char* Begin() { return &(*_buffer.begin()); }
  23.     // 获取当前写入起始地址, _buffer的空间起始地址,加上写偏移量
  24.     char* WritePosition() { return Begin() + _write_index; }
  25.     // 获取当前读取起始地址
  26.     char* ReadPosition() { return Begin() + _read_index; }
  27.     // 获取缓冲区末尾空闲空间大小-->写偏移之后的空闲空间, 总体空间大小减去写偏移
  28.     uint64_t TailSize() { return _buffer.size() - _write_index; }
  29.     // 获取缓冲区起始空闲空间大小-->读偏移之前的空闲空间
  30.     uint64_t BeginSize() { return _read_index; }
  31.     // 获取可读数据大小 = 写偏移 - 读偏移
  32.     uint64_t ReadAbleSize(){ return _write_index - _read_index; }
  33.     // 将读偏移向后移动
  34.     void MoveRead(uint64_t len)
  35.     {
  36.         assert(len <= ReadAbleSize());
  37.         _read_index += len;
  38.     }
  39.     // 将写偏移向后移动
  40.     void MoveWrite(uint64_t len)
  41.     {
  42.         assert(len <= TailSize());
  43.         _write_index += len;
  44.     }
  45.     // 确保可写空间足够(整体空闲空间够了就移动数据,否则就扩容)
  46.     void EnsureWriteSpace(uint64_t len)
  47.     {
  48.         if(TailSize() >= len)
  49.         {
  50.             return;
  51.         }
  52.         else
  53.         {
  54.             if(TailSize() + BeginSize() >= len)
  55.             {
  56.                 uint64_t size = ReadAbleSize();
  57.                 std::copy(ReadPosition(), ReadPosition() + size, Begin());  //把可读数据拷贝到起始位置
  58.                 _read_index = 0;
  59.                 _write_index = size;
  60.             }
  61.             else
  62.             {
  63.                 _buffer.resize(_write_index + 3 * len);
  64.             }
  65.         }
  66.     }
  67.     // 写入数据
  68.     void Write(const void* data, uint64_t len)
  69.     {
  70.         if(len == 0)
  71.         {
  72.             return;
  73.         }
  74.         EnsureWriteSpace(len);
  75.         const char* tmp = static_cast<const char*>(data);
  76.         std::copy(tmp, tmp + len, WritePosition());
  77.     }
  78.     void WriteAndPush(const void* data, uint64_t len)
  79.     {
  80.         Write(data, len);
  81.         MoveWrite(len);
  82.     }
  83.     void WriteString(const std::string& data) { Write(data.c_str(), data.size()); }
  84.     void WriteStringAndPush(const std::string& data)
  85.     {
  86.         WriteString(data);
  87.         MoveWrite(data.size());
  88.     }
  89.     void WriteBuffer(Buffer& data)
  90.     {
  91.         Write(data.ReadPosition(), data.ReadAbleSize());
  92.     }
  93.     void WriteBufferAndPush(Buffer& data)
  94.     {
  95.         WriteBuffer(data);
  96.         MoveWrite(data.ReadAbleSize());
  97.     }
  98.     // 读取数据
  99.     void Read(void* buff, uint64_t len)
  100.     {
  101.         assert(ReadAbleSize() >= len);
  102.         std::copy(ReadPosition(), ReadPosition() + len, (char*)buff);
  103.     }
  104.     void ReadAndPop(void* buff, uint64_t len)
  105.     {
  106.         Read(buff, len);
  107.         MoveRead(len);
  108.     }
  109.     std::string ReadString(uint64_t len)
  110.     {
  111.         assert(len <= ReadAbleSize());
  112.         std::string str;
  113.         str.resize(len);
  114.         Read(&str[0], len);
  115.         return str;
  116.     }
  117.     std::string ReadStringAndPop(uint64_t len)
  118.     {
  119.         assert(len <= ReadAbleSize());
  120.         std::string str = ReadString(len);
  121.         MoveRead(len);
  122.         return str;
  123.     }
  124.     //寻找换行字符
  125.     char* FindCRLF()
  126.     {
  127.         char* res = (char*)memchr(ReadPosition(), '\n', ReadAbleSize());
  128.         return res;
  129.     }
  130.     //通常获取一行数据,这种情况针对是
  131.     std::string GetLine()
  132.     {
  133.         char* pos = FindCRLF();
  134.         if(pos == nullptr)
  135.         {
  136.             return "";
  137.         }
  138.         return ReadString(pos - ReadPosition() + 1);
  139.     }
  140.     std::string GetLineAndPop()
  141.     {
  142.         std::string str = GetLine();
  143.         MoveRead(str.size());
  144.         return str;
  145.     }
  146.     void Clear()
  147.     {
  148.         _read_index = 0;
  149.         _write_index = 0;
  150.     }
  151. };
复制代码
4.2 Socket模块

4.2.1 Socket的功能


4.2.2 Socket的实现

(1)Socket类的筹划接口函数:
  1. // 套接字类
  2. #define MAX_LISTEN 1024
  3. class Sock
  4. {
  5. public:
  6.         Sock();
  7.     Sock(int fd);
  8.     ~Sock();
  9.     // 创建套接字
  10.     bool Socket();
  11.     // 绑定地址信息
  12.     bool Bind(const std::string &ip, uint64_t port);
  13.     // 开始监听
  14.     bool Listen(int backlog = MAX_LISTEN);
  15.     // 向服务器发起连接
  16.     bool Connect(const std::string &ip, uint64_t port);
  17.     // 获取新连接
  18.     int Accept();
  19.     // 接收数据
  20.     ssize_t Recv(void* buf, size_t len, int flag = 0);  // 0 阻塞
  21.     // 发送数据
  22.     ssize_t Send(void* buf, size_t len, int flag = 0);
  23.     // 关闭套接字
  24.     void Close();
  25.     // 创建一个服务器连接
  26.     bool CreateServer(uint64_t port, const std::string &ip = "0.0.0.0"); // 接收全部
  27.     // 创建一个客户端连接
  28.     bool CreateClient(uint64_t port, const std::string &ip);
  29.     // 设置套接字选项 -- 开启地址端口重用
  30.     void ReuseAddress();
  31.     // 设置套接字阻塞属性 -- 设置为非阻塞
  32.     void NonBlock();
  33.    
  34. private:
  35.         int _sockfd;
  36. };  
复制代码
(2)Socket类接口函数实现:
  1. #pragma once
  2. #include <iostream>
  3. #include <string>
  4. #include <unistd.h>
  5. #include <cstring>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <sys/socket.h>
  9. #include <arpa/inet.h>
  10. #include <netinet/in.h>
  11. #include "Log.hpp"
  12. enum
  13. {
  14.     SocketErr = 2,
  15.     BindErr,
  16.     ListenErr,
  17. };
  18. const int backlog = 10;
  19. class Sock
  20. {
  21. public:
  22.     Sock()
  23.     {}
  24.     Sock(int sockfd)
  25.         :_fd(sockfd)
  26.     {}
  27.     bool Socket()
  28.     {
  29.         _fd = socket(AF_INET, SOCK_STREAM, 0);
  30.         if(_fd < 0)
  31.         {
  32.             std::cerr << "socket error" << std::endl;
  33.             return false;
  34.         }
  35.         int opt = 1;
  36.         setsockopt(_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
  37.         return true;
  38.     }
  39.     bool Bind(const std::string& ip, const uint16_t& port)
  40.     {
  41.         sockaddr_in local;
  42.         local.sin_family = AF_INET;
  43.         local.sin_port = htons(port);
  44.         local.sin_addr.s_addr = inet_addr(ip.c_str());
  45.         int n = bind(_fd, (const sockaddr*)&local, sizeof(local));
  46.         if(n < 0)
  47.         {
  48.             std::cerr << "bind error" << std::endl;
  49.             return false;
  50.         }
  51.         return true;
  52.     }
  53.     bool Listen()
  54.     {
  55.         int n = listen(_fd, backlog);
  56.         if(n < 0)
  57.         {
  58.             std::cerr << "listen error" << std::endl;
  59.             return false;
  60.         }
  61.         return true;
  62.     }
  63.     int Accept(std::string& clientip, uint16_t& clientport)
  64.     {
  65.         sockaddr_in client;
  66.         socklen_t len = 0;
  67.         //std::cout << "sssss" << std::endl;
  68.         int fd = accept(_fd, (sockaddr*)&client, &len);
  69.         if(fd < 0)
  70.         {
  71.             std::cerr << "accept error" << std::endl;
  72.             exit(-1);
  73.         }
  74.         char buffer[64];
  75.         inet_ntop(AF_INET, &client.sin_addr, buffer, sizeof(buffer));
  76.         clientip = buffer;
  77.         clientport = ntohs(client.sin_port);
  78.         return fd;
  79.     }
  80.     int Accept()
  81.     {
  82.         sockaddr_in client;
  83.         socklen_t len = 0;
  84.         //std::cout << "sssss" << std::endl;
  85.         int fd = accept(_fd, (sockaddr*)&client, &len);
  86.         if(fd < 0)
  87.         {
  88.             std::cerr << "accept error" << std::endl;
  89.             exit(-1);
  90.         }
  91.         return fd;
  92.     }
  93.     bool Connect(const std::string& serverip, const uint16_t serverport)
  94.     {
  95.         sockaddr_in server;
  96.         server.sin_family = AF_INET;
  97.         server.sin_port = htons(serverport);
  98.         server.sin_addr.s_addr = inet_addr(serverip.c_str());
  99.         int n = connect(_fd, (sockaddr*)&server, sizeof(server));
  100.         if(n < 0)
  101.         {
  102.             std::cerr << "conncet error" << std::endl;
  103.             return false;
  104.         }
  105.         return true;
  106.     }
  107.     ssize_t Recv(void* buf, size_t len, int flag = 0)
  108.     {
  109.         ssize_t n = recv(_fd, buf, len, flag);
  110.         if(n <= 0)
  111.         {
  112.             if(errno == EAGAIN  || errno == EINTR)
  113.             {
  114.                 return 0;  //表示这次接收没有接收到数据
  115.             }
  116.             lg(Fatal, "SOCKET RECV FAILED!!");
  117.             return -1;
  118.         }
  119.         return n;
  120.     }
  121.     ssize_t NonBlockRecv(void* buf, size_t len)
  122.     {
  123.         return Recv(buf, len, MSG_DONTWAIT); // MSG_DONTWAIT 表示当前接收为非阻塞。
  124.     }
  125.     //发送数据
  126.     ssize_t Send(const void* buf, size_t len, int flag = 0)
  127.     {
  128.         ssize_t n = send(_fd, buf, len, flag);
  129.         if(n <= 0)
  130.         {
  131.             if(errno == EAGAIN  || errno == EINTR)
  132.             {
  133.                 return 0;  //表示这次接收没有接收到数据
  134.             }
  135.             lg(Fatal, "SOCKET SEND FAILED!!");
  136.         }
  137.         return n;
  138.     }
  139.     ssize_t NonBlockSend(void* buf, size_t len)
  140.     {
  141.         if (len == 0)
  142.         {
  143.             return 0;
  144.         }
  145.         return Send(buf, len, MSG_DONTWAIT); // MSG_DONTWAIT 表示当前发送为非阻塞。
  146.     }
  147.     //创建一个服务端连接
  148.     bool CreateServer(uint16_t port, const std::string& ip = "0.0.0.0", bool block_flag = false)
  149.     {
  150.         if (Socket() == false) return false;
  151.         if (block_flag) NonBlock();
  152.         if (Bind(ip, port) == false) return false;
  153.         if (Listen() == false) return false;
  154.         return true;
  155.     }
  156.     //创建一个客户端连接
  157.     bool CreateClient(uint16_t port, const std::string &ip)
  158.     {
  159.         //1. 创建套接字,2.指向连接服务器
  160.         if (Socket() == false) return false;
  161.         if (Connect(ip, port) == false) return false;
  162.         return true;
  163.     }
  164.     void Close()
  165.     {
  166.         close(_fd);
  167.     }
  168.     int Getfd()
  169.     {
  170.         return _fd;
  171.     }
  172.     //设置套接字阻塞属性-- 设置为非阻塞
  173.     void NonBlock()
  174.     {
  175.         //int fcntl(int fd, int cmd, ... /* arg */ );
  176.         int flag = fcntl(_fd, F_GETFL, 0);
  177.         fcntl(_fd, F_SETFL, flag | O_NONBLOCK);
  178.     }
  179.     ~Sock()
  180.     {
  181.         Close();
  182.     }
  183. private:
  184.     int _fd;
  185. };
复制代码
4.3 TimeQueue模块

4.3.1 TimeQueue的功能

模块先容:实现固定时间,执行定时任务的模块 — 定时任务管理器。向该模块添加一个任务,任务将在固定时间后被执行,同时也可以对定时任务举行刷新,延迟该任务执行,固然也可以通过接口取消定时任务。
时间轮是一种 实现延迟功能(定时器)的巧妙算法。如果一个系统存在大量的任务调度,时间轮可以高效的利用线程资源来举行批量化调度。把大批量的调度任务全部都绑定时间轮上,通过时间轮举行全部任务的管理,触发以及运行。能够高效地管理各种延时任务,周期任务,通知任务等。
4.3.2 时间轮的头脑





  • 如上图所示,时间轮的实现通过定义数组模拟,而且有一个秒针指向数组的起始位置,这个指针向后走,走到哪里代表哪里的任务要被执行,假设我们要一个任务5秒后执行,只需要将任务添加到_second_hand + 5的位置,秒针每秒向后走一步,5秒后秒针指向对应的位置,定时任务执行。
  • 需要注意的是,在同一时间,可能会有大批量的定时任务。因此我们只需要在数组对应的位置下拉一个数组即可。这样就可以在同一时候添加多个任务了。
4.3.3 定时器任务TimerTask类

(1)类的详细功能:

(2)详细实现如下:
  1. using TaskFunc = std::function<void()>;
  2. using ReleaseFunc = std::function<void()>;
  3. class TimerTask
  4. {
  5. private:
  6.     uint64_t _id;       // 定时器任务对象ID
  7.     uint32_t _timeout;  //定时任务的超时时间
  8.     bool _canceled;     // false-表示没有被取消, true-表示被取消
  9.     TaskFunc _task_cb;  //定时器对象要执行的定时任务
  10.     ReleaseFunc _release; //用于删除TimerWheel中保存的定时器对象信息
  11. public:
  12.     TimerTask(uint64_t id, uint32_t delay, const TaskFunc &cb)
  13.         :_id(id)
  14.         ,_timeout(delay)
  15.         ,_task_cb(cb)
  16.         ,_canceled(false)
  17.     {}
  18.     ~TimerTask()
  19.     {
  20.         if(_canceled == false)
  21.         {
  22.             _task_cb();
  23.         }
  24.         _release();
  25.     }
  26.     void Cancel() { _canceled = true; }
  27.     void SetRelease(const ReleaseFunc &cb) { _release = cb; }
  28.     uint32_t DelayTime() { return _timeout; }
  29. };
复制代码
4.3.4 TimerWheel 类

(1)类的详细功能:



  • 该模块主要是对Connection对象的生命周期举行管理,对非活跃连接举行超时后的释放。
  • 该模块内部包含有一个timerfd。以下是timefd相关函数的认识:



  • 该模块内部含有一个Channel对象:实现对timerfd的变乱就绪回调处理。
(2)详细实现如下:
  1. class TimerWheel
  2. {
  3. private:
  4.     using WeakTask = std::weak_ptr<TimerTask>;
  5.     using PtrTask = std::shared_ptr<TimerTask>;
  6.     int _tick;     // 当前的秒针,走到哪里释放哪里,释放哪里,就相当于执行哪里的任务
  7.     int _capacity; // 表盘最大数量---其实就是最大延迟时间
  8.     std::vector<std::vector<PtrTask>> _wheel;
  9.     std::unordered_map<uint64_t, WeakTask> _timers;
  10.     EventLoop *_loop;
  11.     int _timerfd; // 定时器描述符--可读事件回调就是读取计数器,执行定时任务
  12.     std::unique_ptr<Channel> _timer_channel;
  13. private:
  14.     void RemoveTimer(uint64_t id)
  15.     {
  16.         auto it = _timers.find(id);
  17.         if (it != _timers.end())
  18.         {
  19.             _timers.erase(it);
  20.         }
  21.     }
  22.     static int CreateTimerfd()
  23.     {
  24.         int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
  25.         if (timerfd < 0)
  26.         {
  27.             lg(Fatal, "TIMERFD CREATE FAILED!");
  28.             abort();
  29.         }
  30.         // int timerfd_settime(int fd, int flags, struct itimerspec *new, struct itimerspec *old);
  31.         struct itimerspec itime;
  32.         itime.it_value.tv_sec = 1;
  33.         itime.it_value.tv_nsec = 0; // 第一次超时时间为1s后
  34.         itime.it_interval.tv_sec = 1;
  35.         itime.it_interval.tv_nsec = 0; // 第一次超时后,每次超时的间隔时
  36.         timerfd_settime(timerfd, 0, &itime, NULL);
  37.         return timerfd;
  38.     }
  39.     int ReadTimefd()
  40.     {
  41.         uint64_t times;
  42.         // 有可能因为其他描述符的事件处理花费事件比较长,然后在处理定时器描述符事件的时候,有可能就已经超时了很多次
  43.         // read读取到的数据times就是从上一次read之后超时的次数
  44.         int ret = read(_timerfd, &times, 8);
  45.         if (ret < 0)
  46.         {
  47.             lg(Fatal, "READ TIMEFD FAILED!");
  48.             abort();
  49.         }
  50.         return times;
  51.     }
  52.     // 这个函数应该每秒钟被执行一次,相当于秒针向后走了一步
  53.     void RunTimerTask()
  54.     {
  55.         _tick = (_tick + 1) % _capacity;
  56.         _wheel[_tick].clear(); // 清空指定位置的数组,就会把数组中保存的所有管理定时器对象的shared_ptr释放掉
  57.     }
  58.     void OnTime()
  59.     {
  60.         // 根据实际超时的次数,执行对应的超时任务
  61.         int times = ReadTimefd();
  62.         for (int i = 0; i < times; i++)
  63.         {
  64.             RunTimerTask();
  65.         }
  66.     }
  67.     void TimerAddInLoop(uint64_t id, uint32_t delay, const TaskFunc &cb)
  68.     {
  69.         PtrTask pt(new TimerTask(id, delay, cb));
  70.         pt->SetRelease(std::bind(&TimerWheel::RemoveTimer, this, id));
  71.         int pos = (_tick + delay) % _capacity;
  72.         _wheel[pos].push_back(pt);
  73.         _timers[id] = WeakTask(pt);
  74.     }
  75.     void TimerRefreshInLoop(uint64_t id)
  76.     {
  77.         // 通过保存的定时器对象的weak_ptr构造一个shared_ptr出来,添加到轮子中
  78.         auto it = _timers.find(id);
  79.         if (it == _timers.end())
  80.         {
  81.             return; // 没找着定时任务,没法刷新,没法延迟
  82.         }
  83.         PtrTask pt = it->second.lock(); // lock获取weak_ptr管理的对象对应的shared_ptr
  84.         int delay = pt->DelayTime();
  85.         int pos = (_tick + delay) % _capacity;
  86.         _wheel[pos].push_back(pt);
  87.     }
  88.     void TimerCancelInLoop(uint64_t id)
  89.     {
  90.         auto it = _timers.find(id);
  91.         if (it == _timers.end())
  92.         {
  93.             return; // 没找着定时任务,没法刷新,没法延迟
  94.         }
  95.         PtrTask pt = it->second.lock();
  96.         if (pt)
  97.             pt->Cancel();
  98.     }
  99. public:
  100.     TimerWheel(EventLoop *loop)
  101.         :_capacity(60)
  102.         ,_tick(0)
  103.         ,_wheel(_capacity)
  104.         ,_loop(loop)
  105.         ,_timerfd(CreateTimerfd())
  106.         ,_timer_channel(new Channel(_loop, _timerfd))
  107.     {
  108.         _timer_channel->SetReadCallback(std::bind(&TimerWheel::OnTime, this));
  109.         _timer_channel->EnableRead(); // 启动读事件监控
  110.     }
  111.     /*定时器中有个_timers成员,定时器信息的操作有可能在多线程中进行,因此需要考虑线程安全问题*/
  112.     /*如果不想加锁,那就把对定期的所有操作,都放到一个线程中进行*/
  113.     void TimerAdd(uint64_t id, uint32_t delay, const TaskFunc &cb);
  114.     // 刷新/延迟定时任务
  115.     void TimerRefresh(uint64_t id);
  116.     void TimerCancel(uint64_t id);
  117.     /*这个接口存在线程安全问题--这个接口实际上不能被外界使用者调用,只能在模块内,在对应的EventLoop线程内执行*/
  118.     bool HasTimer(uint64_t id)
  119.     {
  120.         auto it = _timers.find(id);
  121.         if (it == _timers.end())
  122.         {
  123.             return false;
  124.         }
  125.         return true;
  126.     }
  127. };
  128. void TimerWheel::TimerAdd(uint64_t id, uint32_t delay, const TaskFunc &cb)
  129. {
  130.     _loop->RunInLoop(std::bind(&TimerWheel::TimerAddInLoop, this, id, delay, cb));
  131. }
  132. //刷新/延迟定时任务
  133. void TimerWheel::TimerRefresh(uint64_t id)
  134. {
  135.     _loop->RunInLoop(std::bind(&TimerWheel::TimerRefreshInLoop, this, id));
  136. }
  137. void TimerWheel::TimerCancel(uint64_t id)
  138. {
  139.     _loop->RunInLoop(std::bind(&TimerWheel::TimerCancelInLoop, this, id));
  140. }
复制代码
4.4 Any模块

4.4.1 Any的功能



  • Connection模块中需要设置协议处理的上下⽂来控制处理节奏。但是应⽤层协议有许多,这个协议接收解析上下⽂就不能有明显的协议倾向,它可以是任意协议的上下⽂信息,因此就需要⼀个通⽤的类型来生存各种不同的数据结构。
  • Any内部筹划⼀个模板容器holder类,可以生存各种类型数据。因为在Any类中⽆法定义这个holder对象或指针,因为Any也不知道这个类要生存什么类型的数据,因此⽆法传递类型参数。以是,定义⼀个基类placehoder,让holder继续于placeholde,⽽Any类生存⽗类指针即可。当需要生存数据时,则new⼀个带有模板参数的⼦类holder对象出来生存数据,然后让Any类中的⽗类指针,指向这个⼦类对象就搞定了。

4.4.2 Any的实现

详细实现如下:
  1. class Any
  2. {
  3. private:
  4.     class holder
  5.     {
  6.     public:
  7.         virtual ~holder() {}
  8.         virtual const std::type_info &type() = 0;
  9.         virtual holder *clone() = 0;
  10.     };
  11.     template <class T>
  12.     class placeholder : public holder
  13.     {
  14.     public:
  15.         placeholder(const T &val) : _val(val) {}
  16.         // 获取子类对象保存的数据类型
  17.         virtual const std::type_info &type() { return typeid(T); }
  18.         // 针对当前的对象自身,克隆出一个新的子类对象
  19.         virtual holder *clone() { return new placeholder(_val); }
  20.     public:
  21.         T _val;
  22.     };
  23.     holder *_content;
  24. public:
  25.     Any() : _content(NULL) {}
  26.     template <class T>
  27.     Any(const T &val) : _content(new placeholder<T>(val)) {}
  28.     Any(const Any &other) : _content(other._content ? other._content->clone() : NULL) {}
  29.     ~Any() { delete _content; }
  30.     Any &swap(Any &other)
  31.     {
  32.         std::swap(_content, other._content);
  33.         return *this;
  34.     }
  35.     // 返回子类对象保存的数据的指针
  36.     template <class T>
  37.     T *get()
  38.     {
  39.         // 想要获取的数据类型,必须和保存的数据类型一致
  40.         assert(typeid(T) == _content->type());
  41.         return &((placeholder<T> *)_content)->_val;
  42.     }
  43.     // 赋值运算符的重载函数
  44.     template <class T>
  45.     Any &operator=(const T &val)
  46.     {
  47.         // 为val构造一个临时的通用容器,然后与当前容器自身进行指针交换,临时对象释放的时候,原先保存的数据也就被释放
  48.         Any(val).swap(*this);
  49.         return *this;
  50.     }
  51.     Any &operator=(const Any &other)
  52.     {
  53.         Any(other).swap(*this);
  54.         return *this;
  55.     }
  56. };
复制代码
4.5 Channel模块

4.5.1 Channel的功能


模块先容:该模块的主要功能是对每一个形貌符上的IO变乱举行管理,实现对形貌符可读,可写,错误等变乱的管理操纵。以及,Poller模块对形貌符举行IO变乱监控 的变乱就绪后,根据变乱,回调不同的函数。
4.5.2 Channel的实现

(1)Channel类的筹划接口函数:
  1. class Channel
  2. {
  3. public:
  4.     Channel();
  5.     void SetReadCallback(const EventCallback &cb);
  6.     void SetWriteCallback(const EventCallback &cb);
  7.     void SetErrorCallback(const EventCallback &cb);
  8.     void SetCloseCallback(const EventCallback &cb);
  9.     void SetEventCallback(const EventCallback &cb);
  10.     bool ReadAble();     // 当前是否监控了可读
  11.     bool WriteAble();    // 当前是否监控了可写
  12.     void EnableRead();   // 启动读事件监控
  13.     void EnableWrite();  // 启动写事件监控
  14.     void DisableRead();  // 关闭读事件监控
  15.     void DisableWrite(); // 关闭写事件监控
  16.     void Remove();       // 移除监控
  17.     void HandleEvent();  // 事件处理,一旦触发了事件,就调用这个函数,自己触发了什么事件如何处理自己决定
  18.    
  19. private:
  20.         int _fd;
  21.         EventLoop* _loop;
  22.     uint32_t _events;  // 当前需要监控的事件
  23.     uint32_t _revents; // 当前连接触发的事件
  24.     using EventCallback = std::function<void()>;
  25.     EventCallback _read_callback;  // 可读事件被触发的回调函数
  26.     EventCallback _write_callback; // 可写事件被触发的回调函数
  27.     EventCallback _error_callback; // 错误事件被触发的回调函数
  28.     EventCallback _close_callback; // 连接断开事件被触发的回调函数
  29.     EventCallback _event_callback; // 任意事件被触发的回调函数
  30. };
复制代码
(2)Channel类接口函数实现:
  1. class Poller;
  2. class EventLoop;
  3. class Channel
  4. {
  5. private:
  6.     using EventCallback = std::function<void()>;
  7.     EventCallback _read_callback;   //读事件
  8.     EventCallback _write_callback;  //写事件
  9.     EventCallback _error_callback;  //错误事件
  10.     EventCallback _close_callback;  //连接断开事件
  11.     EventCallback _event_callback;  //任意事件
  12.     int _sockfd;
  13.     uint32_t _events;   //监控事件
  14.     uint32_t _revents;  //连接触发事件
  15.     EventLoop* _loop;
  16. public:
  17.     Channel(EventLoop* loop, int sockfd)
  18.         :_sockfd(sockfd)
  19.         ,_events(0)
  20.         ,_revents(0)
  21.         ,_loop(loop)
  22.     {}
  23.     int Getfd(){ return _sockfd; }
  24.     //获取想要监控的事件
  25.     uint32_t GetEvents() { return _events; }
  26.     //设置实际就绪的事件
  27.     void SetEvents(uint32_t events) { _revents = events; }
  28.     void SetReadCallback(const EventCallback& cb) { _read_callback = cb; }
  29.     void SetWriteCallback(const EventCallback& cb) { _write_callback = cb; }
  30.     void SetErrorCallback(const EventCallback& cb) { _error_callback = cb; }
  31.     void SetCloseCallback(const EventCallback& cb) { _close_callback = cb; }
  32.     void SetEventCallback(const EventCallback& cb) { _event_callback = cb; }
  33.     //当前是否监控了可读
  34.     bool Readable() { return (_events & EPOLLIN); }
  35.     //当前是否监控了可写
  36.     bool Writeable() { return (_events & EPOLLOUT); }
  37.     void EnableRead() { _events |= EPOLLIN; UpData(); }
  38.     void EnableWrite() { _events |= EPOLLOUT; UpData(); }
  39.     void DisableRead() { _events &= ~EPOLLIN; UpData(); }
  40.     void DisableWrite() { _events &= ~EPOLLOUT; UpData(); }
  41.     void DisableAll() { _events = 0; UpData(); }
  42.     void Remove();
  43.     void UpData();
  44.     void HanderEvent()
  45.     {
  46.         if((_revents & EPOLLIN) || (_revents & EPOLLRDHUP) || (_revents & EPOLLPRI))
  47.         {
  48.             if(_read_callback)
  49.             {
  50.                 _read_callback();
  51.             }
  52.         }
  53.         if(_revents & EPOLLOUT)
  54.         {
  55.             if(_write_callback)
  56.             {
  57.                 _write_callback();
  58.             }
  59.         }
  60.         else if(_revents & EPOLLERR)
  61.         {
  62.             if(_error_callback)
  63.             {
  64.                 _error_callback();
  65.             }
  66.         }
  67.         else if(_revents & EPOLLHUP)
  68.         {
  69.             if(_close_callback)
  70.             {
  71.                 _close_callback();
  72.             }
  73.         }
  74.         if(_event_callback)
  75.         {
  76.             _event_callback();
  77.         }
  78.     }
  79. };
  80. void Channel::UpData() { _loop->UpdateEvent(this); }
  81. void Channel::Remove() { _loop->RemoveEvent(this); }
复制代码
Channel模块需要和EventLoop模块一起才可以举行测试,因此Channel类的代码只举行了编译测试,测试发现并没有语法上的错误,后面有什么逻辑的错误只能等后续完善该类的时候再来举行测试了。
4.6 Acceptor模块

4.6.1 Acceptor的功能

(1)模块先容对Socket和Channel模块的团体封装,实现对一个监听套接字的团体管理。



  • 该模块中包含一个Socket对象,实现监听套接字的操纵。
  • 该模块中包含一个Channel对象,实现监听套接字IO变乱就绪的处理。
(2)Accept模块处理流程:

  • 向Channel提供可读变乱的IO变乱处理回调函数 — 获取新连接。
  • 为新连接构建一个Connection对象,通过该对象设置各种回调。
4.6.2 Acceptor的实现

(1)Acceptor类的筹划接口函数:
  1. // 监听套接字管理类
  2. class Acceptor
  3. {
  4. public:
  5.         Acceptor();
  6.     void SetAcceptCallback();
  7.    
  8. private:
  9.         /*监听套接字的读事件回调处理函数 -- 获取新连接,调用_accept_callback函数进行新连接管理*/
  10.     void HandleRead();
  11.    
  12.     //启动服务器
  13.         int CreateServer(int port)
  14.    
  15.     Sock _socket;   // 用于创建监听套接字
  16.     EventLoop *_loop; // 用于对监听套接字进行事件监控
  17.     Channel _channel; // 用于对监控套接字进行事件管理
  18.    
  19.     using AcceptCallback = std::function<void(int)>;
  20.     AcceptCallback _accept_callback;
  21. };
复制代码
(2)Acceptor类接口函数实现:
  1. class Acceptor
  2. {
  3. private:
  4.     Sock _socket;
  5.     EventLoop* _loop;
  6.     Channel _channel;
  7.     using AcceptCallback = std::function<void(int)>;
  8.     AcceptCallback _accept_callback;
  9. private:
  10.    
  11.     /*监听套接字的读事件回调处理函数---获取新连接,调用_accept_callback函数进行新连接处理*/
  12.     void HandleRead()
  13.     {
  14.         int newfd = _socket.Accept();
  15.         if (newfd < 0)
  16.         {
  17.             return ;
  18.         }
  19.         if (_accept_callback)
  20.         {
  21.             _accept_callback(newfd);
  22.         }
  23.     }
  24.     int Createsockfd(int port)
  25.     {
  26.         bool ret = _socket.CreateServer(port);
  27.         assert(ret == true);
  28.         return _socket.Getfd();
  29.     }
  30. public:
  31.     Acceptor(EventLoop* loop, int port)
  32.         :_loop(loop)
  33.         ,_socket(Createsockfd(port))
  34.         ,_channel(loop, _socket.Getfd())
  35.     {
  36.         _channel.SetReadCallback(std::bind(&Acceptor::HandleRead, this));
  37.     }
  38.     void SetAcceptCallback(const AcceptCallback &cb) { _accept_callback = cb; }
  39.     void Listen() { _channel.EnableRead(); }
  40. };
复制代码
4.7 Poller模块

4.7.1 Poller的功能


模块先容对epoll举行封装,主要实现epoll的IO变乱添加,修改,移除,获取活跃连接功能。
4.7.2 Poller的实现

(1)笔墨形貌Poller类接口的详细筹划:

(2)Poller类的筹划接口函数:
  1. //Poller描述符监控类
  2. #define MAX_EPOLLEVENTS
  3. class Poller
  4. {
  5. public:
  6.         Poller();
  7.     // 添加或修改监控事件
  8.     void UpdateEvent(Channel *channel);
  9.     // 移除监控
  10.     void RemoveEvent(Channel *channel);
  11.     // 开始监控, 返回活跃连接
  12.     void Poll(std::vector<Channel*> *active);
  13.    
  14. private:
  15.     // 对epoll的直接操作
  16.     void Update(Channel *channel, int op);
  17.     bool HasChannel(Channel *Channel);
  18.    
  19. private:
  20.     int _epfd;
  21.     struct epoll_event _evs[MAX_EPOLLEVENTS];
  22.     std::unordered_map<int, Channel *> _channels;
  23. };
复制代码
(3)Poller类接口函数实现:
  1. #define MAX_EPOLLEVENTS 1024
  2. class Poller
  3. {
  4. private:
  5.     int _epfd;
  6.     epoll_event _revs[MAX_EPOLLEVENTS];
  7.     std::unordered_map<int, Channel*> _channels;
  8.     bool HasChannel(Channel* channel)
  9.     {
  10.         auto iter = _channels.find(channel->Getfd());
  11.         if(iter == _channels.end())
  12.         {
  13.             return false;
  14.         }
  15.         return true;
  16.     }
  17.     void UpData(Channel* channel, int op)
  18.     {
  19.         epoll_event ev;
  20.         ev.events = channel->GetEvents();
  21.         ev.data.fd = channel->Getfd();
  22.         int n = epoll_ctl(_epfd, op, channel->Getfd(), &ev);
  23.         if(n < 0)
  24.         {
  25.             lg(Fatal, "epoll_ctl error!");
  26.         }
  27.     }
  28. public:
  29.     Poller()
  30.     {
  31.         _epfd = epoll_create(MAX_EPOLLEVENTS);
  32.         if(_epfd < 0)
  33.         {
  34.             lg(Fatal, "epoll_create1 error!");
  35.             abort();
  36.         }
  37.     }
  38.     void UpDataEvent(Channel* channel)
  39.     {
  40.         bool ret = HasChannel(channel);
  41.         if(ret == false)
  42.         {
  43.             _channels.insert(std::make_pair(channel->Getfd(), channel));
  44.             return UpData(channel, EPOLL_CTL_ADD);
  45.         }
  46.         UpData(channel, EPOLL_CTL_MOD);
  47.     }
  48.     void RemoveEvent(Channel* channel)
  49.     {
  50.         auto iter = _channels.find(channel->Getfd());
  51.         if (iter != _channels.end())
  52.         {
  53.             _channels.erase(iter);
  54.         }
  55.         UpData(channel, EPOLL_CTL_DEL);
  56.     }
  57.     void Poll(std::vector<Channel*>& active)
  58.     {
  59.         int n = epoll_wait(_epfd, _revs, MAX_EPOLLEVENTS, -1);
  60.         if(n < 0)
  61.         {
  62.             if(errno == EINTR)
  63.             {
  64.                 return;
  65.             }
  66.             lg(Fatal, "epoll_wait error!");
  67.             abort();
  68.         }
  69.         else
  70.         {
  71.             for(int i = 0; i < n; i++)
  72.             {
  73.                 auto iter = _channels.find(_revs[i].data.fd);
  74.                 assert(iter != _channels.end());
  75.                 iter->second->SetEvents(_revs[i].events);
  76.                 active.push_back(iter->second);
  77.             }
  78.         }
  79.     }
  80. };
复制代码
4.8 EventLoop模块

4.8.1 EventLoop的功能

模块先容EventLoop模块对Poller,TimerQueue,Socket模块举行了封装。也是Reactor模型模块。

4.8.2 EventLoop的实现

(1)笔墨形貌EventLoop类接口的详细筹划:


  • EventLoop模块必须是一个对象对应一个线程,线程内部运行EventLoop的启动函数。
  • EventLoop模块为了保证整个服务器的线程安全标题,因此要求使用者对于Connection的全部操纵一定要在其对应的EventLoop线程内完成。
  • EventLoop模块保证本身内部所监控的全部形貌符都要是活跃连接,非活跃连接就要及时的释放避免资源浪费。
  • EventLoop模块内部包含一个eventfd:内核提供的变乱fd,专门用于变乱通知。



  • EventLoop模块内部含有一个Poller对象,用于举行形貌符的IO变乱管理。
  • EventLoop模块内部包含有一个TimeQueue对象,用于举行定时任务的管理。
  • EventLoop模块中包含一个任务队列,组件使用者要对Connection举行的全部操纵,都参加到任务队列中并由EventLoop模块举行管理,并在EventLoop对应的线程中举行执行。
  • 每一个Connection对象都会绑定到一个EventLoop上,这样一来对连接的全部操纵就能保证在一个线程中举行。
  • 通过Poller模块对当前模块管理内的全部形貌符举行IO变乱监控,当有形貌符变乱就绪后,通过形貌符对应的Channel举行变乱的处理。
  • 全部就绪的形貌符IO变乱处理完毕后,对任务队列中的全部操纵举行顺序执行。
  • epoll的变乱监控,有可能会因为没有变乱到来而持续壅闭。导致任务队列中的任务不能得到及时的处理。对此的处理方式是创建一个eventfd,添加到Poller的变乱监控中,每当向任务队列添加任务的时候,通过向eventdf写入数据来唤醒epoll的壅闭。
(2)EventLoop类的筹划接口函数:
  1. // EventLoop事件监控处理类
  2. class EventLoop
  3. {
  4. public:
  5.         using Functor = std::function<void()>;
  6.     EventLoop();
  7.     void RunInLoop(const Functor &cb); // 判断将要执行的任务是否处于当前线程中,如果是则执行,否则压入队列
  8.     void QueueInLoop(const Functor &cb); // 将操作压入任务池
  9.     bool IsInLoop(); // 用于判断当前线程是否是EventLoop对应的线程
  10.     void UpdateEvent(Channel *channel); // 添加/修改描述符的事件监控
  11.     void RemoveEvent(Channel *channel); // 移除描述符的监控
  12.     void Start(); // 三步走--事件监控-》就绪事件处理-》执行任务
  13.     void RunAllTask();
  14.    
  15. private:
  16.     std::thread::id _thread_id; //线程ID
  17.     int _event_fd;  //eventfd唤醒IO事件监控有可能导致的阻塞
  18.     std::unique_ptr<Channel> _event_channel;
  19.     Poller _poller;
  20.     std::vector<Functor> _tasks;
  21.     std::mutex _mutex;  //实现任务池操作的线程安全
  22.     TimerWheel _timer_wheel;  //定时器模块
  23. };
复制代码
(3)EventLoop类接口函数实现:
  1. class EventLoop
  2. {
  3. private:
  4.     using Functor = std::function<void()>;
  5.     std::thread::id _thread_id;
  6.     int _event_fd;
  7.     std::unique_ptr<Channel> _event_channel;
  8.     Poller _poller;
  9.     std::vector<Functor> _tasks;
  10.     std::mutex _mutex;    //实现任务池操作的线程安全
  11.     TimerWheel _timer_wheel;//定时器模块
  12. public:
  13.     EventLoop()
  14.         :_event_fd(CreateEventfd())
  15.         ,_event_channel(new Channel(this, _event_fd))
  16.         ,_thread_id(std::this_thread::get_id())
  17.         ,_timer_wheel(this)
  18.     {
  19.         _event_channel->SetReadCallback(std::bind(&EventLoop::ReadEventfd, this));
  20.         _event_channel->EnableRead();
  21.     }
  22.     void Start()
  23.     {
  24.         while(1)
  25.         {
  26.             std::vector<Channel*> actives;
  27.             _poller.Poll(actives);
  28.             for(auto& channel : actives)
  29.             {
  30.                 channel->HanderEvent();
  31.             }
  32.             RunAllTask();
  33.         }
  34.     }
  35.     //用于判断当前线程是否是EventLoop对应的线程;
  36.     bool IsInLoop() { return (_thread_id == std::this_thread::get_id()); }
  37.     void AssertInLoop() { assert(_thread_id == std::this_thread::get_id()); }
  38.     void RunInLoop(const Functor& cb)
  39.     {
  40.         if(IsInLoop())
  41.         {
  42.             cb();
  43.         }
  44.         else
  45.         {
  46.             QueueInLoop(cb);
  47.         }
  48.     }
  49.     void QueueInLoop(const Functor& cb)
  50.     {
  51.         {
  52.             std::unique_lock<std::mutex> _lock(_mutex);
  53.             _tasks.push_back(cb);
  54.         }
  55.         WeakEventfd();
  56.     }
  57.     //添加/修改描述符的事件监控
  58.     void UpdateEvent(Channel* channel) { _poller.UpDataEvent(channel); }
  59.     void RemoveEvent(Channel* channel) { _poller.RemoveEvent(channel); }
  60.     void TimerAdd(uint64_t id, uint32_t delay, const TaskFunc &cb) { return _timer_wheel.TimerAdd(id, delay, cb); }
  61.    
  62.     void TimerRefresh(uint64_t id) { return _timer_wheel.TimerRefresh(id); }
  63.    
  64.     void TimerCancel(uint64_t id) { return _timer_wheel.TimerCancel(id); }
  65.    
  66.     bool HasTimer(uint64_t id) { return _timer_wheel.HasTimer(id); }
  67. public:
  68.     void RunAllTask()
  69.     {
  70.         std::vector<Functor> functor;
  71.         {
  72.             std::unique_lock<std::mutex> _lock(_mutex);
  73.             _tasks.swap(functor);
  74.         }
  75.         for (auto& f : functor)
  76.         {
  77.             f();
  78.         }
  79.     }
  80.     static int CreateEventfd()
  81.     {
  82.         int efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
  83.         if(efd < 0)
  84.         {
  85.             lg(Fatal, "eventfd error!");
  86.             abort();
  87.         }
  88.         return efd;
  89.     }
  90.     void ReadEventfd()
  91.     {   
  92.         uint64_t res = 0;
  93.         int ret = read(_event_fd, &res, sizeof(res));
  94.         if(ret < 0)
  95.         {
  96.             //EINTR -- 被信号打断;   EAGAIN -- 表示无数据可读
  97.             if (errno == EINTR || errno == EAGAIN)
  98.             {
  99.                 return;
  100.             }
  101.             lg(Fatal, "READ EVENTFD FAILED!");
  102.             abort();
  103.         }
  104.     }
  105.     void WeakEventfd()
  106.     {
  107.         uint64_t val = 1;
  108.         int ret = write(_event_fd, &val, sizeof(val));
  109.         if(ret < 0)
  110.         {
  111.             //EINTR -- 被信号打断;   EAGAIN -- 表示无数据可读
  112.             if (errno == EINTR || errno == EAGAIN)
  113.             {
  114.                 return;
  115.             }
  116.             lg(Fatal, "write EVENTFD FAILED!");
  117.             abort();
  118.         }
  119.     }
  120. };
复制代码
4.9 Connection模块

4.9.1 Connection的功能

模块先容该模块是一个对Buffer/Socket/Channel模块的团体封装,实现了对套接字的团体管理。每一个举行数据通讯的套接字(accept获取到的新连接)都会构造一个Connetction对象举行管理。

4.9.2 Connection的实现

(1)模块分析:

  • 该模块内部包含由组件使用者提供的回调函数:连接建立完成回调,变乱回调,新数据回调,关闭回调。
  • 该模块包含两个组件使用者提供的接口,数据发送接口和连接关闭接口。
  • 该模块中包含两个用户态缓冲区:用户态接收缓冲区和用户态发送缓冲区。
  • 该模块中包含一个Socket对象,完成形貌符面向系统的IO操纵。
  • 该模块中包含一个Channel对象,完成形貌符IO变乱就绪的处理。
(2)该模块的处理流程:

  • 向Channel提供可读,可写,错误等不同变乱的IO变乱回调函数,将Channel和对应的形貌符添加到Poller变乱监控中。
  • 当形貌符在Poller模块中就绪了IO可读变乱后,调用该形貌符对应Channel中生存的读变乱处理函数,举行数据读取,读取的过程本质上是将socket接收缓冲区中的数据 读到Connection管理的用户态接收数据中。
  • 业务处理完毕后,通过Connection提供的数据发送接口,将数据写入到Connection的发送缓冲区中。
  • 启动形貌符在Poll模块中的IO变乱监控,变乱就绪后,调用Channel中生存的写变乱处理函数,将发送缓冲区中的数据通过Sockert举行数据的真正发送。
(3)Connection类的筹划接口函数:
  1. // DISCONECTED -- 连接关闭状态  CONNECTING -- 连接建立成功-待处理状态
  2. // CONNECTED -- 连接建立完成,各种设置已完成,可以通信状态    DISCONNECTING -- 待关闭状态
  3. typedef enum
  4. {
  5.     DISCONECTED,
  6.     CONNECTING,
  7.     CONNECTED,
  8.     DISCONNECTING
  9. } ConnStatu;
  10. using PtrConnection = std::shared_ptr<Connection>;
  11. class Connection
  12. {
  13. public:
  14.     Connection(EventLoop *loop, uint64_t conn_id, int sockfd);
  15.     ~Connection();
  16.     int Fd();                            // 获取管理的文件描述符
  17.     int Id();                            // 获取连接ID
  18.     bool Connected();                    // 是否处于CONNECTED状态
  19.     void SetContext(const Any &context); // 设置上下文--连接建立完成时进行调用
  20.     Any *GetContext();                   // 获取上下文,返回的是指针
  21.     void SetConnectedCallback(const ConnectedCallback &cb);
  22.     void SetMessageCallback(const MessageCallback &cb);
  23.     void SetClosedCallback(const ClosedCallback &cb);
  24.     void SetAnyEventCallback(const AnyEventCallback &cb);
  25.     void Established();                  // 连接建立就绪后,进行channel回调设置,启动读监控,调用_connect_callback
  26.     void Send(char *data, size_t len);   // 发送数据,将数据发送到发送缓冲区,启动写事件监控
  27.     void Shutdown();                     // 提供给组件使用者的关闭接口--并不实际关闭,需要判断有没有数据待处理
  28.     void EnableInactiveRelease(int sec); // 启动非活跃销毁,并定义多长时间无通信就是非活跃,添加定时任务
  29.     void CancelInactiveRelease();        // 取消非活跃销毁
  30.     // 切换协议--重置上下文以及阶段性处理函数
  31.     void Upgrade(const Context, const ConnectedCallback &conn,
  32.                  const ClosedCallback &closed, const AnyEventCallback &event);
  33. private:
  34.     /*五个channel的事件回调函数*/
  35.     void HandleRead();        // 描述符可读事件触发后调用的函数,接收socket数据放到接收缓冲区中,然后调用_message_callback
  36.     void HandleWrite();       // 描述符可写事件触发后调用的函数,将发送缓冲区中的数据进行发送
  37.     void HandleClose();       // 描述符触发挂断事件
  38.     void HandleError();       // 描述符触发出错事件
  39.     void HandleEvent();       // 描述符触发任意事件
  40.     void EstablishedInLoop(); // 连接获取之后,所处的状态要进行各种设置(给channel设置事件回调,启动读监控)
  41.     void ReleaseInLoop();     // 这个接口才是实际的释放接口
  42.     void SendInLoop(char *data, size_t len);
  43.     void ShutdownInLoop();
  44.     void EnableInactiveReleaseInLoop(int sec);
  45.     void CancelInactiveReleaseInLoop();
  46.     void UpgradeInLoop(const Context &context,
  47.                        const ConnectedCallback &conn,
  48.                        const MessageCallback &msg,
  49.                        const ClosedCallback &closed,
  50.                        const AnyEventCallback &event);
  51. private:
  52.     uint64_t _conn_id; // 连接的唯一ID,便于连接的管理和查找
  53.     // uint64_t _timer_id; // 定时器ID,必须是唯一的,这块是为了简化操作使用conn_id作为定时器
  54.     int _sockfd;                   // 连接关联的文件描述符
  55.     bool _enable_inactive_release; // 连接是否启动非活跃的判断标志,默认为false
  56.     EventLoop *_loop;              // 连接所关联的一个EventLoop
  57.     ConnStatu _statu;              // 连接状态
  58.     Socket _socket;                // 套接字操作管理
  59.     Channel _channel;              // 连接的事件管理
  60.     Buffer _in_buffer;             // 输入缓冲区--存放从socket中读取到的数据
  61.     Buffer _out_buffer;            // 输出缓冲区--存放要发送给对端的数据
  62.     Any _context;                  // 请求的接收处理上下文
  63.     /*这四个回调函数,是让服务器模块来设置的(其实服务器模块的处理回调也是组件使用者设置的)*/
  64.     /*换句话来说,这几个回调都是组件使用者使用的*/
  65.     using ConnectedCallback = std::function<void(const PtrConnection &)>;
  66.     using MessageCallback = std::function<void(const PtrConnection &, Buffer *)>;
  67.     using ClosedCallback = std::function<void(const PtrConnection &)>;
  68.     using AnyEventCallback = std::function<void(const PtrConnection &)>;
  69.     ConnectedCallback _connected_callback;
  70.     MessageCallback _message_callback;
  71.     ClosedCallback _closef_callback;
  72.     AnyEventCallback _event_callback;
  73.     /*组件内的连接关闭回调--组件内设置的,因为服务器组件内会把所有的连接管理起来,一旦某个连接要关闭*/
  74.     /*就应该从管理的地方移除掉自己的信息*/
  75.     ClosedCallback _server_closed_callback;
  76. };
复制代码
(4)Connection类接口函数实现:
  1. class Connection;
  2. //DISCONECTED -- 连接关闭状态;   CONNECTING -- 连接建立成功-待处理状态
  3. //CONNECTED -- 连接建立完成,各种设置已完成,可以通信的状态;  DISCONNECTING -- 待关闭状态
  4. typedef enum { DISCONNECTED, CONNECTING, CONNECTED, DISCONNECTING}ConnStatu;
  5. using PtrConnection = std::shared_ptr<Connection>;
  6. class Connection : public std::enable_shared_from_this<Connection>
  7. {
  8. private:
  9.     uint64_t _conn_id;  // 连接的唯一ID,便于连接的管理和查找
  10.     int _sockfd;
  11.     bool _enable_inactive_release; // 连接是否启动非活跃销毁的判断标志,默认为false
  12.     EventLoop* _loop;   // 连接所关联的一个EventLoop
  13.     ConnStatu _statu;
  14.     Sock _socket;
  15.     Channel _channel;
  16.     Buffer _in_buffer;
  17.     Buffer _out_buffer;
  18.     Any _context;
  19.     //这几个回调都是组件使用者使用的
  20.     using ConnectedCallback = std::function<void(const PtrConnection &)>;
  21.     using MessageCallback = std::function<void(const PtrConnection &, Buffer *)>;
  22.     using ClosedCallback = std::function<void(const PtrConnection &)>;
  23.     using AnyEventCallback = std::function<void(const PtrConnection &)>;
  24.     ConnectedCallback _connected_callback;
  25.     MessageCallback _message_callback;
  26.     ClosedCallback _closed_callback;
  27.     AnyEventCallback _event_callback;
  28.     //组件内的连接关闭回调--组件内设置的,因为服务器组件内会把所有的连接管理起来,一旦某个连接要关闭
  29.     //就应该从管理的地方移除掉自己的信息
  30.     ClosedCallback _server_closed_callback;
  31. private:
  32.     void HanderRead()
  33.     {
  34.         char buf[65536];
  35.         ssize_t ret = _socket.NonBlockRecv(buf, sizeof(buf));
  36.         if(ret < 0)
  37.         {
  38.             return ShutdownInLoop();
  39.         }
  40.         _in_buffer.WriteAndPush(buf, ret);
  41.         if(_in_buffer.ReadAbleSize() > 0)
  42.         {
  43.             return _message_callback(shared_from_this(), &_in_buffer);
  44.         }
  45.     }
  46.     void HanderWrite()
  47.     {
  48.         ssize_t ret = _socket.NonBlockSend(_out_buffer.ReadPosition(), _out_buffer.ReadAbleSize());
  49.         if(ret < 0)
  50.         {
  51.             // 发送错误就该关闭连接了,
  52.             if (_in_buffer.ReadAbleSize() > 0)
  53.             {
  54.                 _message_callback(shared_from_this(), &_in_buffer);
  55.             }
  56.             return Release(); // 这时候就是实际的关闭释放操作了。
  57.         }
  58.         _out_buffer.MoveRead(ret);
  59.         if (_out_buffer.ReadAbleSize() == 0)
  60.         {
  61.             _channel.DisableWrite(); // 没有数据待发送了,关闭写事件监控
  62.             // 如果当前是连接待关闭状态,则有数据,发送完数据释放连接,没有数据则直接释放
  63.             if (_statu == DISCONNECTING)
  64.             {
  65.                 return Release();
  66.             }
  67.         }
  68.     }
  69.     void HanderClose()
  70.     {
  71.         //一旦连接挂断了,套接字就什么都干不了了,因此有数据待处理就处理一下,完毕关闭连接
  72.         if (_in_buffer.ReadAbleSize() > 0)
  73.         {
  74.             _message_callback(shared_from_this(), &_in_buffer);
  75.         }
  76.         return Release();
  77.     }
  78.     void HanderError()
  79.     {
  80.         HanderClose();
  81.     }
  82.     //描述符触发任意事件: 1. 刷新连接的活跃度--延迟定时销毁任务;  2. 调用组件使用者的任意事件回调
  83.     void HandleEvent()
  84.     {
  85.         if(_enable_inactive_release  == true)
  86.         {
  87.             _loop->TimerRefresh(_conn_id);
  88.         }
  89.         if(_event_callback)
  90.         {
  91.             _event_callback(shared_from_this());
  92.         }
  93.     }
  94.     //连接获取之后,所处的状态下要进行各种设置(启动读监控,调用回调函数)
  95.     void EstablishedInLoop()
  96.     {
  97.         assert(_statu == CONNECTING);//当前的状态必须一定是上层的半连接状态
  98.         _statu = CONNECTED;
  99.         _channel.EnableRead();
  100.         if(_connected_callback)
  101.         {
  102.             _connected_callback(shared_from_this());
  103.         }
  104.     }
  105.     //这个接口才是实际的释放接口
  106.     void ReleaseInLoop()
  107.     {
  108.         _statu = DISCONNECTED;
  109.         _channel.Remove();
  110.         _socket.Close();
  111.         // 如果当前定时器队列中还有定时销毁任务,则取消任务
  112.         if (_loop->HasTimer(_conn_id)) CancelInactiveReleaseInLoop();
  113.         // 调用关闭回调函数,避免先移除服务器管理的连接信息导致Connection被释放,再去处理会出错,因此先调用用户的回调函数
  114.         if (_closed_callback) _closed_callback(shared_from_this());
  115.         // 移除服务器内部管理的连接信息
  116.         if (_server_closed_callback) _server_closed_callback(shared_from_this());
  117.     }
  118.     //这个接口并不是实际的发送接口,而只是把数据放到了发送缓冲区,启动了可写事件监控
  119.     void SendInLoop(Buffer &buf)
  120.     {
  121.         if(_statu == DISCONNECTED)
  122.         {
  123.             return;
  124.         }
  125.         _out_buffer.WriteBufferAndPush(buf);
  126.         if (_channel.Writeable() == false)
  127.         {
  128.             _channel.EnableWrite();
  129.         }
  130.     }
  131.     //这个关闭操作并非实际的连接释放操作,需要判断还有没有数据待处理,待发送
  132.     void ShutdownInLoop()
  133.     {
  134.         _statu = DISCONNECTING;// 设置连接为半关闭状态
  135.         if(_in_buffer.ReadAbleSize() > 0)
  136.         {
  137.             if(_message_callback)
  138.             {
  139.                 _message_callback(shared_from_this(), &_in_buffer);
  140.             }
  141.         }
  142.         //要么就是写入数据的时候出错关闭,要么就是没有待发送数据,直接关闭
  143.         if(_out_buffer.ReadAbleSize() > 0)
  144.         {
  145.             if(_channel.Writeable() == false)
  146.             {
  147.                 _channel.EnableWrite();
  148.             }
  149.         }
  150.         if(_out_buffer.ReadAbleSize() == 0)
  151.         {
  152.             Release();
  153.         }
  154.     }
  155.     //启动非活跃连接超时释放规则
  156.     void EnableInactiveReleaseInLoop(int sec)
  157.     {
  158.         // 1. 将判断标志 _enable_inactive_release 置为true
  159.         _enable_inactive_release = true;
  160.         // 2. 如果当前定时销毁任务已经存在,那就刷新延迟一下即可
  161.         if(_loop->HasTimer(_conn_id))
  162.         {
  163.             return _loop->TimerRefresh(_conn_id);
  164.         }
  165.         // 3. 如果不存在定时销毁任务,则新增
  166.         _loop->TimerAdd(_conn_id, sec, std::bind(&Connection::Release, this));
  167.     }
  168.     void CancelInactiveReleaseInLoop()
  169.     {
  170.         _enable_inactive_release = false;
  171.         if(_loop->HasTimer(_conn_id))
  172.         {
  173.             _loop->TimerCancel(_conn_id);
  174.         }
  175.     }
  176.     void UpgradeInLoop(const Any &context,
  177.                        const ConnectedCallback &conn,
  178.                        const MessageCallback &msg,
  179.                        const ClosedCallback &closed,
  180.                        const AnyEventCallback &event)
  181.     {
  182.         _context = context;
  183.         _connected_callback = conn;
  184.         _message_callback = msg;
  185.         _closed_callback = closed;
  186.         _event_callback = event;
  187.     }
  188. public:
  189.     Connection(EventLoop* loop, uint64_t conn_id, int sockfd)
  190.         :_conn_id(conn_id)
  191.         ,_sockfd(sockfd)
  192.         ,_enable_inactive_release(false)
  193.         ,_loop(loop)
  194.         ,_statu(CONNECTING)
  195.         ,_socket(sockfd)
  196.         ,_channel(loop, _sockfd)
  197.     {
  198.         _channel.SetReadCallback(std::bind(&Connection::HanderRead, this));
  199.         _channel.SetWriteCallback(std::bind(&Connection::HanderWrite, this));
  200.         _channel.SetCloseCallback(std::bind(&Connection::HanderClose, this));
  201.         _channel.SetErrorCallback(std::bind(&Connection::HanderError, this));
  202.         _channel.SetEventCallback(std::bind(&Connection::HandleEvent, this));
  203.     }
  204.     int Getfd() { return _sockfd; }
  205.     int Getid() { return _conn_id; }
  206.     //是否处于CONNECTED状态
  207.     bool Connected() { return (_statu == CONNECTED); }
  208.     //设置上下文--连接建立完成时进行调用
  209.     void SetContext(const Any &context) { _context = context; }
  210.     //获取上下文,返回的是指针
  211.     Any* GetContext() { return &_context; }
  212.     void SetConnectedCallback(const ConnectedCallback &cb) { _connected_callback = cb; }
  213.     void SetMessageCallback(const MessageCallback &cb) { _message_callback = cb; }
  214.     void SetClosedCallback(const ClosedCallback &cb) { _closed_callback = cb; }
  215.     void SetAnyEventCallback(const AnyEventCallback &cb) { _event_callback = cb; }
  216.     void SetSrvClosedCallback(const ClosedCallback &cb) { _server_closed_callback = cb; }
  217.     void Established()
  218.     {
  219.         _loop->RunInLoop(std::bind(&Connection::EstablishedInLoop, this));
  220.     }
  221.     void Send(const char* data, size_t len)
  222.     {
  223.         Buffer buf;
  224.         buf.WriteAndPush(data, len);
  225.         _loop->RunInLoop(std::bind(&Connection::SendInLoop, this, std::move(buf)));
  226.     }
  227.     void Shutdown()
  228.     {
  229.         _loop->RunInLoop(std::bind(&Connection::ShutdownInLoop, this));
  230.     }
  231.     void Release()
  232.     {
  233.         _loop->QueueInLoop(std::bind(&Connection::ReleaseInLoop, this));
  234.     }
  235.     //启动非活跃销毁,并定义多长时间无通信就是非活跃,添加定时任务
  236.     void EnableInactiveRelease(int sec)
  237.     {
  238.         _loop->RunInLoop(std::bind(&Connection::EnableInactiveReleaseInLoop, this, sec));
  239.     }
  240.     //取消非活跃销毁
  241.     void CancelInactiveRelease()
  242.     {
  243.         _loop->RunInLoop(std::bind(&Connection::CancelInactiveReleaseInLoop, this));
  244.     }
  245.     void Upgrade(const Any &context, const ConnectedCallback &conn, const MessageCallback &msg,
  246.                  const ClosedCallback &closed, const AnyEventCallback &event)
  247.     {
  248.         _loop->AssertInLoop();
  249.         _loop->RunInLoop(std::bind(&Connection::UpgradeInLoop, this, context, conn, msg, closed, event));
  250.     }
  251. };
复制代码
4.10 LoopThreadPool模块

4.10.1 LoopThreadPool的功能




  • LoopThread模块的功能就是将EventLoop模块与thread整合到一起。
  • EventLoop模块实例化的对象,在构造的时候会初始化_thread_id。在后续的操纵中,通过当前线程ID和EventLoop模块中的_thread_id举行一个比较,相同就表示在同一个线程,不同就表示当前运行的线程并不是EventLoop线程。因此,我们必须先创建线程,然后在线程的入口函数中,去实例化EventLoop对象。
  • LoopThreadPool模块的功能主要是对全部的LoopThread举行管理及分配。
  • 在服务器中,主Reactor负责新连接的获取,附属线程负责新连接的变乱监控及处理,因此当前的线程池,游有可能附属线程数量为0。也就是实现单Reactor服务器,一个线程既负责获取连接,也负责连接的处理。该模块就是对0个大概多个LoopThread对象举行管理。
关于线程分配,当主线程获取了一个新连接,需要将新连接挂到附属线程上举行变乱监控及处理。假设有0个附属线程,则直接分配给主线程的EventLoop举行处理。假设有多个附属线程,采用轮转的头脑,举行线程的分配(将对应线程的EventLoop获取到,设置给对应的Connection)。
在实现LoopThreadPool类之前需要实现LoopThread类。
4.10.2 LoopThread的功能

EventLoop模块在实例化对象的时候,必须在线程内部,EventLoop在实例化对象时会设置本身的thread_id,如果我们先创建了多个EventLoop对象,然后创建了多个线程,将各个线程的id,重新给EventLoop举行设置存在标题:那就是在构造EventLoop对象,到设置新的thread_id期间将是不可控的。
因此我们必须先创建线程,然后在线程的入口函数中,去实例化EventLoop对象构造一个新的模块:LoopThread。该模块的功能是将EventLoop与thread整合到一起:

  • 创建线程
  • 在线程中实例化EventLoop对象
LoopThread功能:可以向外部返回所实例化的EventLoop。
4.10.3 LoopThread的实现

详细实现如下:
  1. class LoopThread
  2. {
  3. private:
  4.     std::mutex _mutex;
  5.     std::condition_variable _cond;
  6.     EventLoop* _loop;       // EventLoop指针变量,这个对象需要在线程内实例化
  7.     std::thread _thread;    // EventLoop对应的线程
  8.     /*实例化 EventLoop 对象,唤醒_cond上有可能阻塞的线程,并且开始运行EventLoop模块的功能*/
  9.     void ThreadEntry()
  10.     {
  11.         EventLoop loop;
  12.         {
  13.             std::unique_lock<std::mutex> lock(_mutex);//加锁
  14.             _loop = &loop;
  15.             _cond.notify_all();
  16.         }
  17.         loop.Start();
  18.     }
  19. public:
  20.     LoopThread()
  21.         :_loop(nullptr)
  22.         ,_thread(std::thread(&LoopThread::ThreadEntry, this))
  23.     {}
  24.     EventLoop* GetLoop()
  25.     {
  26.         EventLoop* loop;
  27.         {
  28.             std::unique_lock<std::mutex> lock(_mutex);
  29.             _cond.wait(lock, [&](){ return _loop != NULL; });
  30.             loop = _loop;
  31.         }
  32.         return loop;
  33.     }
  34. };
复制代码
4.10.4 LoopThreadPool的实现

LoopThreadPool类接口函数实现:
  1. class LoopThreadPool
  2. {
  3. private:
  4.     int _thread_count;
  5.     int _next_idx;
  6.     EventLoop* _baseloop;
  7.     std::vector<LoopThread*> _threads;
  8.     std::vector<EventLoop*> _loops;
  9. public:
  10.     LoopThreadPool(EventLoop* baseloop)
  11.         :_baseloop(baseloop)
  12.         ,_thread_count(0)
  13.         ,_next_idx(0)
  14.     {}
  15.     void SetThreadCount(int count) { _thread_count = count; }
  16.     void Create()
  17.     {
  18.         if(_thread_count > 0)
  19.         {
  20.             _threads.resize(_thread_count);
  21.             _loops.resize(_thread_count);
  22.             for(int i = 0; i < _thread_count; i++)
  23.             {
  24.                 _threads[i] = new LoopThread();
  25.                 _loops[i] = _threads[i]->GetLoop();
  26.             }
  27.         }
  28.     }
  29.     EventLoop* NextLoop()
  30.     {
  31.         if(_thread_count == 0)
  32.         {
  33.             return _baseloop;
  34.         }
  35.         _next_idx = (_next_idx + 1) % _thread_count;
  36.         return _loops[_next_idx];
  37.     }
  38. };
复制代码
4.11 TcpServer模块

4.11.1 TcpServer模块的功能

TcpServer模块功能:对全部模块的整合,通过TcpServer模块实例化的对象,可以非常简单的完成一个服务器的搭建。
(1)TcpServer模块的管理:

  • Acceptor对象,创建一个监听套接字。
  • EventLoop对象, baseloop对象, 实现对监听套接字的变乱监控。
  • std::unordered_ map <uint64_ t, PtrConnection> conns, 实现对全部新建连接的管理。
  • LoopThreadPool对象,创建loop线程池, 对新建连接举行变乱监控及处理。
(2)TcpServer模块的主要功能:

  • 设置附属线程池数量。
  • 启动服务器。
  • 设置各种回调函数(连接建立完成,消息,关闭,任意), 用户设置给TcpServer, TcpServer设置给获取的新连接。
  • 是否启动非活跃连接超时烧毁功能。
  • 添加定时任务功能。
(3)TcpServer模块的工作流程:

  • 在TcpServer中实例化一个Acceptor对象, 以及一个EventLoop对象(baseloop)。
  • 将Acceptor挂到baseloop上举行变乱监控。
  • 一旦Acceptor对象就绪了可读变乱,则执行读变乱回调函数获取新建连接。
  • 对新连接创建一个Connection举行管理。
  • 对连接对应的Connection设置功能回调(连接完成回调,消息回调,关闭回调,任意变乱回调)。
  • 启动Connection的非活跃连接的超时烧毁规则。
  • 将新连接对应的Connection挂到LoopThreadPool中的附属线程对应的Eventloop中举行变乱监控。
  • 一旦Connection对应的连接就绪了可读变乱,则这时候执行读变乱回调函数,读取数据,读取完毕后调用TcpServer设置的消息回调。
4.11.2 TcpServer模块的实现

(1)TcpServer类的筹划接口函数:
  1. // TcpServer服务器管理模块(即全部模块的整合)
  2. class TcpServer
  3. {
  4. private:
  5.     uint64_t _next_id;                                  // 这是一个自动增长的连接ID
  6.     int _port;
  7.     int _timeout;                                       // 这是非活跃连接的统计时间--多长时间无通信就是非活跃连接
  8.     bool _enable_inactive_release;                      // 是否启动非活跃连接超时销毁的判断标志
  9.     EventLoop _baseloop;                                // 这是主线程的EventLoop对象,负责监听事件的处理
  10.     Acceptor _acceptor;                                 // 这是监听套接字的管理对象
  11.     LoopThreadPool _pool;                               // 这是从属EventLoop线程池
  12.     std::unordered_map<uint64_t, PtrConnection> _conns; // 保管所有连接对应的share_ptr对象,这里面的对象被删除,就意味这某一个连接被删除
  13.     using ConnectedCallback = std::function<void(const PtrConnection &)>;
  14.     using MessageCallback = std::function<void(const PtrConnection &, Buffer *)>;
  15.     using ClosedCallback = std::function<void(const PtrConnection &)>;
  16.     using AnyEventCallback = std::function<void(const PtrConnection &)>;
  17.     using Functor = std::function<void()>;
  18.     ConnectedCallback _connected_callback;
  19.     MessageCallback _message_callback;
  20.     ClosedCallback _closed_callback;
  21.     AnyEventCallback _event_callback;
  22. private:
  23.     void NewConnection(int fd); // 为新连接构造一个Connection进行管理
  24.     void RemoveConnection(); // 从管理Connection的_conns移除连接信息
  25. public:
  26.     TcpServer();
  27.     void SetThreadCount(int count);
  28.     void SetConnectedCallback(const ConnectedCallback &cb) { _connected_callback = cb; }
  29.     void SetMessageCallback(const MessageCallback &cb) { _message_callback = cb; }
  30.     void SetClosedCallback(const ClosedCallback &cb) { _closed_callback = cb; }
  31.     void SetAnyEventCallback(const AnyEventCallback &cb) { _event_callback = cb; }
  32.     void EnableInactiveRelease(int timeout);
  33.     void RunAfter(const Functor &task, int delay);  // 用于添加一个定时任务
  34.     void Start();
  35. };
复制代码
(2)TcpServer类的筹划接口函数实现:
  1. class TcpServer
  2. {
  3. private:
  4.     uint64_t _next_id; //这是一个自动增长的连接ID,
  5.     int _port;
  6.     int _timeout;
  7.     bool _enable_inactive_release;
  8.     EventLoop _base_loop;
  9.     Acceptor _acceptor;
  10.     LoopThreadPool _pool;   //这是从属EventLoop线程池
  11.     std::unordered_map<uint64_t, PtrConnection> _conns; //保存管理所有连接对应的shared_ptr对象
  12.     using ConnectedCallback = std::function<void(const PtrConnection&)>;
  13.     using MessageCallback = std::function<void(const PtrConnection&, Buffer *)>;
  14.     using ClosedCallback = std::function<void(const PtrConnection&)>;
  15.     using AnyEventCallback = std::function<void(const PtrConnection&)>;
  16.     using Functor = std::function<void()>;
  17.     ConnectedCallback _connected_callback;
  18.     MessageCallback _message_callback;
  19.     ClosedCallback _closed_callback;
  20.     AnyEventCallback _event_callback;
  21. private:
  22.     void NewConnection(int fd)
  23.     {
  24.         _next_id++;
  25.         PtrConnection conn(new Connection(_pool.NextLoop(), _next_id, fd));
  26.         conn->SetMessageCallback(_message_callback);
  27.         conn->SetClosedCallback(_closed_callback);
  28.         conn->SetConnectedCallback(_connected_callback);
  29.         conn->SetAnyEventCallback(_event_callback);
  30.         conn->SetSrvClosedCallback(std::bind(&TcpServer::RemoveConnection, this, std::placeholders::_1));
  31.         if(_enable_inactive_release)
  32.         {
  33.             conn->EnableInactiveRelease(_timeout); //启动非活跃超时销毁
  34.         }
  35.         conn->Established();//就绪初始化
  36.         _conns.insert(std::make_pair(_next_id, conn));
  37.     }
  38.     void RunAfterInLoop(const Functor &task, int delay)
  39.     {
  40.         _next_id++;
  41.         _base_loop.TimerAdd(_next_id, delay, task);
  42.     }
  43.     void RemoveConnectionInLoop(const PtrConnection& conn)
  44.     {
  45.         int id = conn->Getid();
  46.         auto iter = _conns.find(id);
  47.         if(iter != _conns.end())
  48.         {
  49.             _conns.erase(id);
  50.         }
  51.     }
  52.     void RemoveConnection(const PtrConnection& conn)
  53.     {
  54.         _base_loop.RunInLoop(std::bind(&TcpServer::RemoveConnectionInLoop, this, conn));
  55.     }
  56. public:
  57.     TcpServer(int port)
  58.         :_port(port)
  59.         ,_next_id(0)
  60.         ,_enable_inactive_release(false)
  61.         ,_acceptor(&_base_loop, port)
  62.         ,_pool(&_base_loop)
  63.     {
  64.         _acceptor.SetAcceptCallback(std::bind(&TcpServer::NewConnection, this, std::placeholders::_1));
  65.         _acceptor.Listen();   //将监听套接字挂到baseloop上
  66.     }
  67.     void SetThreadCount(int count) { return _pool.SetThreadCount(count); }
  68.     void SetConnectedCallback(const ConnectedCallback&cb) { _connected_callback = cb; }
  69.     void SetMessageCallback(const MessageCallback&cb) { _message_callback = cb; }
  70.     void SetClosedCallback(const ClosedCallback&cb) { _closed_callback = cb; }
  71.     void SetAnyEventCallback(const AnyEventCallback&cb) { _event_callback = cb; }
  72.     void EnableInactiveRelease(int timeout) { _timeout = timeout; _enable_inactive_release = true; }
  73.    
  74.     //用于添加一个定时任务
  75.     void RunAfter(const Functor &task, int delay)
  76.     {
  77.         _base_loop.RunInLoop(std::bind(&TcpServer::RunAfterInLoop, this, task, delay));
  78.     }
  79.     void Start() { _pool.Create();  _base_loop.Start(); }
  80. };
  81. class NetWork
  82. {
  83. public:
  84.     NetWork()
  85.     {
  86.         lg(Info, "SIGPIPE INIT");
  87.         signal(SIGPIPE, SIG_IGN);
  88.     }
  89. };
  90. static NetWork nw;
复制代码
5. Http协议模块

5.1 Util模块

(1)该模块为工具模块,主要提供Http协议模块所用到的一些工具函数,比如Url编码解码,文件读写。

(2)详细功能实现如下:
  1. #pragma once
  2. #include "../server.hpp"
  3. #include <fstream>
  4. #include <ostream>
  5. #include <sys/stat.h>
  6. std::unordered_map<int, std::string> _statu_msg = {
  7.     {100, "Continue"},
  8.     {101, "Switching Protocol"},
  9.     {102, "Processing"},
  10.     {103, "Early Hints"},
  11.     {200, "OK"},
  12.     {201, "Created"},
  13.     {202, "Accepted"},
  14.     {203, "Non-Authoritative Information"},
  15.     {204, "No Content"},
  16.     {205, "Reset Content"},
  17.     {206, "Partial Content"},
  18.     {207, "Multi-Status"},
  19.     {208, "Already Reported"},
  20.     {226, "IM Used"},
  21.     {300, "Multiple Choice"},
  22.     {301, "Moved Permanently"},
  23.     {302, "Found"},
  24.     {303, "See Other"},
  25.     {304, "Not Modified"},
  26.     {305, "Use Proxy"},
  27.     {306, "unused"},
  28.     {307, "Temporary Redirect"},
  29.     {308, "Permanent Redirect"},
  30.     {400, "Bad Request"},
  31.     {401, "Unauthorized"},
  32.     {402, "Payment Required"},
  33.     {403, "Forbidden"},
  34.     {404, "Not Found"},
  35.     {405, "Method Not Allowed"},
  36.     {406, "Not Acceptable"},
  37.     {407, "Proxy Authentication Required"},
  38.     {408, "Request Timeout"},
  39.     {409, "Conflict"},
  40.     {410, "Gone"},
  41.     {411, "Length Required"},
  42.     {412, "Precondition Failed"},
  43.     {413, "Payload Too Large"},
  44.     {414, "URI Too Long"},
  45.     {415, "Unsupported Media Type"},
  46.     {416, "Range Not Satisfiable"},
  47.     {417, "Expectation Failed"},
  48.     {418, "I'm a teapot"},
  49.     {421, "Misdirected Request"},
  50.     {422, "Unprocessable Entity"},
  51.     {423, "Locked"},
  52.     {424, "Failed Dependency"},
  53.     {425, "Too Early"},
  54.     {426, "Upgrade Required"},
  55.     {428, "Precondition Required"},
  56.     {429, "Too Many Requests"},
  57.     {431, "Request Header Fields Too Large"},
  58.     {451, "Unavailable For Legal Reasons"},
  59.     {501, "Not Implemented"},
  60.     {502, "Bad Gateway"},
  61.     {503, "Service Unavailable"},
  62.     {504, "Gateway Timeout"},
  63.     {505, "HTTP Version Not Supported"},
  64.     {506, "Variant Also Negotiates"},
  65.     {507, "Insufficient Storage"},
  66.     {508, "Loop Detected"},
  67.     {510, "Not Extended"},
  68.     {511, "Network Authentication Required"}
  69. };
  70. std::unordered_map<std::string, std::string> _mime_msg = {
  71.     {".aac", "audio/aac"},
  72.     {".abw", "application/x-abiword"},
  73.     {".arc", "application/x-freearc"},
  74.     {".avi", "video/x-msvideo"},
  75.     {".azw", "application/vnd.amazon.ebook"},
  76.     {".bin", "application/octet-stream"},
  77.     {".bmp", "image/bmp"},
  78.     {".bz", "application/x-bzip"},
  79.     {".bz2", "application/x-bzip2"},
  80.     {".csh", "application/x-csh"},
  81.     {".css", "text/css"},
  82.     {".csv", "text/csv"},
  83.     {".doc", "application/msword"},
  84.     {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
  85.     {".eot", "application/vnd.ms-fontobject"},
  86.     {".epub", "application/epub+zip"},
  87.     {".gif", "image/gif"},
  88.     {".htm", "text/html"},
  89.     {".html", "text/html"},
  90.     {".ico", "image/vnd.microsoft.icon"},
  91.     {".ics", "text/calendar"},
  92.     {".jar", "application/java-archive"},
  93.     {".jpeg", "image/jpeg"},
  94.     {".jpg", "image/jpeg"},
  95.     {".js", "text/javascript"},
  96.     {".json", "application/json"},
  97.     {".jsonld", "application/ld+json"},
  98.     {".mid", "audio/midi"},
  99.     {".midi", "audio/x-midi"},
  100.     {".mjs", "text/javascript"},
  101.     {".mp3", "audio/mpeg"},
  102.     {".mpeg", "video/mpeg"},
  103.     {".mpkg", "application/vnd.apple.installer+xml"},
  104.     {".odp", "application/vnd.oasis.opendocument.presentation"},
  105.     {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
  106.     {".odt", "application/vnd.oasis.opendocument.text"},
  107.     {".oga", "audio/ogg"},
  108.     {".ogv", "video/ogg"},
  109.     {".ogx", "application/ogg"},
  110.     {".otf", "font/otf"},
  111.     {".png", "image/png"},
  112.     {".pdf", "application/pdf"},
  113.     {".ppt", "application/vnd.ms-powerpoint"},
  114.     {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
  115.     {".rar", "application/x-rar-compressed"},
  116.     {".rtf", "application/rtf"},
  117.     {".sh", "application/x-sh"},
  118.     {".svg", "image/svg+xml"},
  119.     {".swf", "application/x-shockwave-flash"},
  120.     {".tar", "application/x-tar"},
  121.     {".tif", "image/tiff"},
  122.     {".tiff", "image/tiff"},
  123.     {".ttf", "font/ttf"},
  124.     {".txt", "text/plain"},
  125.     {".vsd", "application/vnd.visio"},
  126.     {".wav", "audio/wav"},
  127.     {".weba", "audio/webm"},
  128.     {".webm", "video/webm"},
  129.     {".webp", "image/webp"},
  130.     {".woff", "font/woff"},
  131.     {".woff2", "font/woff2"},
  132.     {".xhtml", "application/xhtml+xml"},
  133.     {".xls", "application/vnd.ms-excel"},
  134.     {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
  135.     {".xml", "application/xml"},
  136.     {".xul", "application/vnd.mozilla.xul+xml"},
  137.     {".zip", "application/zip"},
  138.     {".3gp", "video/3gpp"},
  139.     {".3g2", "video/3gpp2"},
  140.     {".7z", "application/x-7z-compressed"}
  141. };
  142. class Util
  143. {
  144. public:
  145.     // 字符串分割函数,将src字符串按照sep字符进行分割,得到的各个字串放到arry中,最终返回字串的数量
  146.     static size_t Split(const std::string &src, const std::string &sep, std::vector<std::string> *arry)
  147.     {
  148.         size_t offset = 0;
  149.         // 有10个字符,offset是查找的起始位置,范围应该是0~9,offset==10就代表已经越界了
  150.         while (offset < src.size())
  151.         {
  152.             // 在src字符串偏移量offset处,开始向后查找sep字符/字串,返回查找到的位置
  153.             size_t pos = src.find(sep, offset);
  154.             if (pos == std::string::npos) // 没有找到特定的字符
  155.             {
  156.                 // 将剩余的部分当作一个字串,放入arry中
  157.                 if (pos == src.size())
  158.                 {
  159.                     break;
  160.                 }
  161.                 arry->push_back(src.substr(offset));
  162.                 return arry->size();
  163.             }
  164.             if (pos == offset)
  165.             {
  166.                 offset = pos + sep.size();
  167.                 continue; // 当前字串是一个空的,没有内容
  168.             }
  169.             arry->push_back(src.substr(offset, pos - offset));
  170.             offset = pos + sep.size();
  171.         }
  172.         return arry->size();
  173.     }
  174.     // 读取文件的所有内容,将读取的内容放到一个Buf中
  175.     static bool ReadFile(const std::string &filename, std::string *buf)
  176.     {
  177.         std::ifstream out(filename, std::ios::binary);
  178.         if (out.is_open() == false)
  179.         {
  180.             LOG(FATAL, "Open ReadFile error");
  181.             return false;
  182.         }
  183.         size_t out_size = 0;
  184.         out.seekg(0, out.end);  // 跳转读写位置到末尾
  185.         out_size = out.tellg(); // 获取当前读写位置相对于起始位置的偏移量,从末尾偏移刚好就是文件大小
  186.         out.seekg(0, out.beg);  // 跳转到起始位置
  187.         buf->resize(out_size);  // 开辟文件大小的空间
  188.         out.read(&(*buf)[0], out_size);
  189.         if (out.good() == false)
  190.         {
  191.             printf("Read %s File error!!", filename.c_str());
  192.             out.close();
  193.             return false;
  194.         }
  195.         out.close();
  196.         return true;
  197.     }
  198.     // 向文件写入数据
  199.     static bool WriteFile(const std::string& filename, std::string& buf)
  200.     {
  201.         std::ofstream in(filename, std::ios::binary);
  202.         if (in.is_open() == false)
  203.         {
  204.             LOG(FATAL, "Open WriteFile error");
  205.             return false;
  206.         }
  207.         in.write(buf.c_str(), buf.size());
  208.         if (in.good() == false)
  209.         {
  210.             LOG(FATAL, "Write File error");
  211.             in.close();
  212.             return false;
  213.         }
  214.         in.close();
  215.         return true;
  216.     }
  217.     // URL编码,避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中特殊字符产生歧义
  218.     // 编码格式:将特殊字符的ascii值,转换为两个16进制字符,前缀%   C++ -> C%2B%2B
  219.     // 不编码的特殊字符: RFC3986文档规定 . - _ ~ 字母,数字属于绝对不编码字符
  220.     // RFC3986文档规定,编码格式 %HH
  221.     // W3C标准中规定,查询字符串中的空格,需要编码为+, 解码则是+转空格
  222.     static std::string UrlEncode(const std::string &url, bool convert_space_to_plus)
  223.     {
  224.         std::string res;
  225.         for (auto &ch : url)
  226.         {
  227.             if (ch == '.' || ch == '-' || ch == '_' || ch == '~' || isalnum(ch))
  228.             {
  229.                 res += ch;
  230.                 continue;
  231.             }
  232.             if (ch == ' ' && convert_space_to_plus == true)
  233.             {
  234.                 res += '+';
  235.                 continue;
  236.             }
  237.             // 剩下的字符都是需要编码成为 %HH 格式
  238.             char tmp[4] = {0};
  239.             // snprintf 与 printf比较类似,都是格式化字符串,只不过一个是打印,一个是放到一块空间中
  240.             snprintf(tmp, 4, "%%%02X", ch);
  241.             res += tmp;
  242.         }
  243.         return res;
  244.     }
  245.     static char HEXTOI(char c)
  246.     {
  247.         if (c >= '0' && c <= '9')
  248.         {
  249.             return c - '0';
  250.         }
  251.         else if (c >= 'a' && c <= 'z')
  252.         {
  253.             return c - 'a' + 10;
  254.         }
  255.         else if (c >= 'A' && c <= 'Z')
  256.         {
  257.             return c - 'A' + 10;
  258.         }
  259.         return -1;
  260.     }
  261.     // Url解码
  262.     static std::string UrlDecode(const std::string &url, bool convert_plus_to_space)
  263.     {
  264.         std::string res;
  265.         for (int i = 0; i < url.size(); i++)
  266.         {
  267.             if (url[i] == '+' && convert_plus_to_space == true)
  268.             {
  269.                 res += ' ';
  270.                 continue;
  271.             }
  272.             if (url[i] == '%' && (i + 2) < url.size())
  273.             {
  274.                 char v1 = HEXTOI(url[i + 1]);
  275.                 char v2 = HEXTOI(url[i + 2]);
  276.                 char v = v1 * 16 + v2;
  277.                 res += v;
  278.                 i += 2;
  279.                 continue;
  280.             }
  281.             res += url[i];
  282.         }
  283.         return res;
  284.     }
  285.     // 响应状态码的描述信息获取
  286.     static std::string StatuDesc(int statu)
  287.     {
  288.         auto it = _statu_msg.find(statu);
  289.         if (it != _statu_msg.end())
  290.         {
  291.             return it->second;
  292.         }
  293.         return "Unknow";
  294.     }
  295.     // 根据文件后缀名获取文件mime
  296.     static std::string ExtMime(const std::string& filename)
  297.     {
  298.         // a.b.txt  先获取文件扩展名
  299.         size_t pos = filename.find_last_of('.');
  300.         if(pos == std::string::npos)
  301.         {
  302.             return "application/octet-stream";
  303.         }
  304.         // 根据扩展名,获取mime
  305.         std::string ext = filename.substr(pos);
  306.         auto it = _mime_msg.find(ext);
  307.         if(it == _mime_msg.end())
  308.         {
  309.             return "application/octet-stream";
  310.         }
  311.         return it->second;
  312.     }
  313.     // 判断一个文件是否是一个目录
  314.     static bool IsDirectory(const std::string &filename)
  315.     {
  316.         struct stat st;
  317.         int ret = stat(filename.c_str(), &st);
  318.         if(ret < 0)
  319.         {
  320.             return false;
  321.         }
  322.         
  323.         return S_ISDIR(st.st_mode);
  324.     }
  325.     // 判断一个文件是否是一个普通文件
  326.     static bool IsRegular(const std::string &filename)
  327.     {
  328.         struct stat st;
  329.         int ret = stat(filename.c_str(), &st);
  330.         if(ret < 0)
  331.         {
  332.             return false;
  333.         }
  334.         
  335.         return S_ISREG(st.st_mode);
  336.     }
  337.     //http请求的资源路径有效性判断
  338.     // /index.html  --- 前边的/叫做相对根目录  映射的是某个服务器上的子目录
  339.     // 想表达的意思就是,客户端只能请求相对根目录中的资源,其他地方的资源都不予理会
  340.     // /../login, 这个路径中的..会让路径的查找跑到相对根目录之外,这是不合理的,不安全的
  341.     static bool ValidPath(const std::string &path)
  342.     {
  343.         //思想:按照/进行路径分割,根据有多少子目录,计算目录深度,有多少层,深度不能小于0
  344.         std::vector<std::string> subdir;
  345.         Split(path, "/", &subdir);
  346.         int level = 0;
  347.         for(auto& dir : subdir)
  348.         {
  349.             if(dir == "..")
  350.             {
  351.                 level--; // 任意一层走出相对根目录,就认为有问题
  352.                 if(level < 0)
  353.                 {
  354.                     return false;
  355.                 }
  356.                 continue;
  357.             }
  358.             level++;
  359.         }
  360.         return true;
  361.     }
  362. };
复制代码
5.2 HttpRequest模块

(1)这个模块是Http请求数据模块,用于生存Http请求数据被解析后的各项请求元素信息。详细功能如下图:

(2)详细实现如下:
  1. #pragma once
  2. #include <iostream>
  3. #include <regex>
  4. #include <unordered_map>
  5. class HttpRequest
  6. {
  7. public:
  8.     std::string _method;      //请求方法
  9.     std::string _path;        //资源路径
  10.     std::string _version;     //协议版本
  11.     std::string _body;        //请求正文
  12.     std::smatch _matches;     //资源路径的正则提取数据
  13.     std::unordered_map<std::string, std::string> _headers;  //头部字段
  14.     std::unordered_map<std::string, std::string> _params;   //查询字符串
  15. public:
  16.     HttpRequest()
  17.         :_version("HTTP/1.1")
  18.     {}
  19.     void ReSet()
  20.     {
  21.         _method.clear();
  22.         _path.clear();
  23.         _version = "HTTP/1.1";
  24.         _body.clear();
  25.         std::smatch match;
  26.         _matches.swap(match);
  27.         _headers.clear();
  28.         _params.clear();
  29.     }
  30.     //插入头部字段
  31.     void SetHeader(const std::string& key, const std::string& val)
  32.     {
  33.         _headers.insert(std::make_pair(key, val));
  34.     }
  35.     bool HasHeader(const std::string& key) const
  36.     {
  37.         auto iter = _headers.find(key);
  38.         if(iter == _headers.end())
  39.         {
  40.             return false;
  41.         }
  42.         return true;
  43.     }
  44.     std::string GetHeader(const std::string& key) const
  45.     {
  46.         auto iter = _headers.find(key);
  47.         if(iter == _headers.end())
  48.         {
  49.             return "";
  50.         }
  51.         return iter->second;
  52.     }
  53.     //插入查询字符串
  54.     void SetParam(const std::string& key, const std::string& val)
  55.     {
  56.         _params.insert(std::make_pair(key, val));
  57.     }
  58.     bool HasParam(const std::string& key) const
  59.     {
  60.         auto it = _params.find(key);
  61.         if (it == _params.end())
  62.         {
  63.             return false;
  64.         }
  65.         return true;
  66.     }
  67.     // 获取指定的查询字符串
  68.     std::string GetParam(const std::string& key) const
  69.     {
  70.         auto it = _params.find(key);
  71.         if (it == _params.end())
  72.         {
  73.             return "";
  74.         }
  75.         return it->second;
  76.     }
  77.     //获取正文长度
  78.     size_t ContentLength() const
  79.     {
  80.         bool ret = HasHeader("Content-Length");
  81.         if(ret == false)
  82.         {
  83.             return 0;
  84.         }
  85.         std::string clen = GetHeader("Content-Length");
  86.         return std::stol(clen);
  87.     }
  88.     // 判断是否是短链接
  89.     bool Close() const
  90.     {
  91.         // 没有Connection字段,或者有Connection但是值是close,则都是短链接,否则就是长连接
  92.         if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
  93.         {
  94.             return false;
  95.         }
  96.         return true;
  97.     }
  98. };
复制代码
5.3 HttpResponse模块

(1)这个模块是Http响应数据块,用于业务处理后设置并生存Http响应数据的各项元素信息,最终会被按照Http协议响应格式构造成为响应信息发送给客户端。详细功能如下图:

(2)详细实现如下:
  1. #pragma once
  2. #include <iostream>
  3. #include <unordered_map>
  4. class HttpResponse
  5. {
  6. public:
  7.     int _statu;
  8.     bool _redirect_flag;
  9.     std::string _body;
  10.     std::string _redirect_url;
  11.     std::unordered_map<std::string, std::string> _headers;
  12. public:
  13.     HttpResponse()
  14.         :_redirect_flag(false)
  15.         ,_statu(200)
  16.     {}
  17.     HttpResponse(int statu)
  18.         :_redirect_flag(false)
  19.         ,_statu(statu)
  20.     {}
  21.     void Reset()
  22.     {
  23.         _statu = 200;
  24.         _redirect_flag = false;
  25.         _body.clear();
  26.         _redirect_url.clear();
  27.         _headers.clear();
  28.     }
  29.     // 插入头部字段
  30.     void SetHeader(const std::string& key, const std::string& val)
  31.     {
  32.         _headers.insert(std::make_pair(key, val));
  33.     }
  34.     // 判断是否存在指定头部字段
  35.     bool HasHeader(const std::string& key)
  36.     {
  37.         auto it = _headers.find(key);
  38.         if (it == _headers.end())
  39.         {
  40.             return false;
  41.         }
  42.         return true;
  43.     }
  44.     // 获取指定头部字段的值
  45.     std::string GetHeader(const std::string& key)
  46.     {
  47.         auto it = _headers.find(key);
  48.         if (it == _headers.end())
  49.         {
  50.             return "";
  51.         }
  52.         return it->second;
  53.     }
  54.     void SetContent(const std::string& body, const std::string& type = "text.html")
  55.     {
  56.         _body = body;
  57.         SetHeader("Content-Type", type);
  58.     }
  59.     void SetRedirect(const std::string& url, int statu = 302)
  60.     {
  61.         _statu = statu;
  62.         _redirect_flag = true;
  63.         _redirect_url = url;
  64.     }
  65.     // 判断是否是短链接
  66.     bool Close()
  67.     {
  68.         // 没有Connection字段,或者有Connection但是值是close,则都是短链接,否则就是长连接
  69.         if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
  70.         {
  71.             return false;
  72.         }
  73.         
  74.         return true;
  75.     }
  76. };
复制代码
5.4 HttpContext模块

(1)该模块是一个Http请求接收的上下文模块,主要是为了防止在一次接收的数据中,不是一个完整的Http请求,需要在下次接收到新数据后继续根据上下文举行解析,最终得到一个HttpRequest请求信息对象,因此在请求数据的接收以及解析部门需要一个上下文来举行控制接收和处理节奏。

(2)正则库的简单概述:
注意在正则表达式的相关函数要在gcc版本较高的版本下才气正常运行,否则会出现编译乐成,但是运行失败的情况。

(3)详细实现如下:
  1. #pragma once
  2. #include <iostream>
  3. #include "HttpRequest.hpp"
  4. #include "Util.hpp"
  5. #include "../Buffer.hpp"
  6. typedef enum {
  7.     RECV_HTTP_ERROR,
  8.     RECV_HTTP_LINE,
  9.     RECV_HTTP_HEAD,
  10.     RECV_HTTP_BODY,
  11.     RECV_HTTP_OVER
  12. }HttpRecvStatu;
  13. #define MAX_LINE 8192
  14. class HttpContext
  15. {
  16. private:
  17.     int _resp_statu; //响应状态码
  18.     HttpRecvStatu _recv_statu; //当前接收及解析的阶段状态
  19.     HttpRequest _request;  //已经解析得到的请求信息
  20. private:
  21.     bool ParseHttpLine(const std::string& line)
  22.     {
  23.         std::smatch matches;
  24.         std::regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase);
  25.         bool ret = std::regex_match(line, matches, e);
  26.         if(ret == false)
  27.         {
  28.             _recv_statu = RECV_HTTP_ERROR;
  29.             _resp_statu = 400; // BAD REQUEST
  30.             return false;
  31.         }
  32.         
  33.         //0 : GET /baidu/login?user=xiaoming&pass=123123 HTTP/1.1
  34.         //1 : GET
  35.         //2 : /bitejiuyeke/login
  36.         //3 : user=xiaoming&pass=123123
  37.         //4 : HTTP/1.1
  38.         //请求方法的获取
  39.         _request._method = matches[1];
  40.         std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
  41.         //资源路径的获取,需要进行URL解码操作,但是不需要+转空格
  42.         _request._path = Util::UrlDecode(matches[2], false);
  43.         //协议版本的获取
  44.         _request._version = matches[4];
  45.         //查询字符串的获取与处理
  46.         std::vector<std::string> query_string_arry;
  47.         std::string query_string = matches[3];
  48.         Util::Split(query_string, "&", &query_string_arry);
  49.         //针对各个字串,以 = 符号进行分割,得到key 和val, 得到之后也需要进行URL解码
  50.         for(auto& ch : query_string_arry)
  51.         {
  52.             size_t pos = ch.find("=");
  53.             if(pos == std::string::npos)
  54.             {
  55.                 _recv_statu = RECV_HTTP_ERROR;
  56.                 _resp_statu = 400;   //BAD REQUEST
  57.                 return false;
  58.             }
  59.             std::string key = Util::UrlDecode(ch.substr(0, pos), true);  
  60.             std::string val = Util::UrlDecode(ch.substr(pos + 1), true);
  61.             _request.SetParam(key, val);
  62.         }
  63.         return true;
  64.     }
  65.     bool RecvHttpLine(Buffer* buf)
  66.     {
  67.         if (_recv_statu != RECV_HTTP_LINE)
  68.         {
  69.             return false;
  70.         }
  71.         //1. 获取一行数据,带有末尾的换行
  72.         std::string line = buf->GetLineAndPop();
  73.         //2. 需要考虑的一些要素:缓冲区中的数据不足一行, 获取的一行数据超大
  74.         if(line.size() == 0)
  75.         {
  76.             // 缓冲区中的数据不足一行,则需要判断缓冲区的可读数据长度,如果很长了都不足一行,这是有问题的
  77.             if(buf->ReadAbleSize() > MAX_LINE)
  78.             {
  79.                 _recv_statu = RECV_HTTP_ERROR;
  80.                 _resp_statu = 414; // URI TOO LONG
  81.                 return false;
  82.             }
  83.             // 缓冲区中数据不足一行,但是也不多,就等等新数据的到来
  84.             return true;
  85.         }
  86.         if(line.size() > MAX_LINE)
  87.         {
  88.             _recv_statu = RECV_HTTP_ERROR;
  89.             _resp_statu = 414;//URI TOO LONG
  90.             return false;
  91.         }
  92.         bool ret = ParseHttpLine(line);
  93.         if(ret == false)
  94.         {
  95.             return false;
  96.         }
  97.         //首行处理完毕,进入头部获取阶段
  98.         _recv_statu = RECV_HTTP_HEAD;
  99.         return true;
  100.     }
  101.     bool RecvHttpHead(Buffer* buf)
  102.     {
  103.         if(_recv_statu != RECV_HTTP_HEAD)
  104.         {
  105.             return false;
  106.         }
  107.         while(1)
  108.         {
  109.             std::string line = buf->GetLineAndPop();
  110.             if(line.size() == 0)
  111.             {
  112.                 // 缓冲区中的数据不足一行,则需要判断缓冲区的可读数据长度,如果很长了都不足一行,这是有问题的
  113.                 if(buf->ReadAbleSize() > MAX_LINE)
  114.                 {
  115.                     _recv_statu = RECV_HTTP_ERROR;
  116.                     _resp_statu = 414; // URI TOO LONG
  117.                     return false;
  118.                 }
  119.                 // 缓冲区中数据不足一行,但是也不多,就等等新数据的到来
  120.                 return true;
  121.             }
  122.             if(line.size() > MAX_LINE)
  123.             {
  124.                 _recv_statu = RECV_HTTP_ERROR;
  125.                 _resp_statu = 414;//URI TOO LONG
  126.                 return false;
  127.             }
  128.             if(line == "\n" || line == "\r\n")
  129.             {
  130.                 break;
  131.             }
  132.             bool ret = ParseHttpHead(line);
  133.             if(ret == false)
  134.             {
  135.                 return false;
  136.             }
  137.         }
  138.         //头部处理完毕,进入正文获取阶段
  139.         _recv_statu = RECV_HTTP_BODY;
  140.         return true;
  141.     }
  142.     bool ParseHttpHead(std::string& line)
  143.     {
  144.         if(line.back() == '\n') line.pop_back();
  145.         if(line.back() == '\r') line.pop_back();
  146.         auto pos = line.find(": ");
  147.         if(pos == std::string::npos)
  148.         {
  149.             _recv_statu = RECV_HTTP_ERROR;
  150.             _resp_statu = 400; //
  151.             return false;
  152.         }
  153.         std::string key = line.substr(0, pos);
  154.         std::string val = line.substr(pos + 2);
  155.         _request.SetHeader(key, val);
  156.         return true;
  157.     }
  158.     bool RecvHttpBody(Buffer* buf)
  159.     {
  160.         if(_recv_statu != RECV_HTTP_BODY)
  161.         {
  162.             return false;
  163.         }
  164.         
  165.         //1. 获取正文长度
  166.         size_t content_length = _request.ContentLength();
  167.         if(content_length == 0)
  168.         {
  169.             //没有正文,则请求接收解析完毕
  170.             _recv_statu = RECV_HTTP_OVER;
  171.             return true;
  172.         }
  173.         //2. 当前已经接收了多少正文,其实就是往  _request._body 中放了多少数据了
  174.         size_t real_len = content_length - _request._body.size();//实际还需要接收的正文长度
  175.         //3. 接收正文放到body中,但是也要考虑当前缓冲区中的数据,是否是全部的正文
  176.         //  3.1 缓冲区中数据,包含了当前请求的所有正文,则取出所需的数据
  177.         if(buf->ReadAbleSize() >= real_len)
  178.         {
  179.             _request._body.append(buf->ReadPosition(), real_len);
  180.             buf->MoveRead(real_len);
  181.             _recv_statu = RECV_HTTP_OVER;
  182.             return true;
  183.         }
  184.         //  3.2 缓冲区中数据,无法满足当前正文的需要,数据不足,取出数据,然后等待新数据到来
  185.         _request._body.append(buf->ReadPosition(), buf->ReadAbleSize());
  186.         buf->MoveRead(buf->ReadAbleSize());
  187.         return true;
  188.     }
  189. public:
  190.     HttpContext()
  191.         :_resp_statu(200)
  192.         ,_recv_statu(RECV_HTTP_LINE)
  193.     {}
  194.     void ReSet()
  195.     {
  196.         _resp_statu = 200;
  197.         _recv_statu = RECV_HTTP_LINE;
  198.         _request.ReSet();
  199.     }
  200.     int RespStatu() { return _resp_statu; }
  201.     HttpRecvStatu RecvStatu() { return _recv_statu; }
  202.     HttpRequest& Request() { return _request; }
  203.     //接收并解析HTTP请求
  204.     void RecvHttpRequest(Buffer* buf)
  205.     {
  206.         //不同的状态,做不同的事情,但是这里不要break
  207.         //因为处理完请求行后,应该立即处理头部,而不是退出等新数据
  208.         switch (_recv_statu)
  209.         {
  210.             case RECV_HTTP_LINE: RecvHttpLine(buf);
  211.             case RECV_HTTP_HEAD: RecvHttpHead(buf);
  212.             case RECV_HTTP_BODY: RecvHttpBody(buf);
  213.         }
  214.     }
  215. };
复制代码
5.5 HttpServer模块

(1)主要目标:最终给组件使用者提供的Http服务器模块,用于以简单的接口实现Http服务器的搭建。

  • HttpServer模块内部包含有⼀个TcpServer对象:TcpServer对象实现服务器的搭建 。
  • HttpServer模块内部包含有两个提供给TcpServer对象的接口:连接建⽴乐成设置上下⽂接口,数据处理接口。
  • HttpServer模块内部包含有⼀个hash-map表存储请求与处理函数的映射表:组件使⽤者向HttpServer设置哪些请求应该使⽤哪些函数进⾏处理,等TcpServer收到对应的请求就会使⽤对应的函数进⾏处理。
(2)详细实现如下:
  1. #pragma once
  2. #include "HttpRequest.hpp"
  3. #include "HttpResponse.hpp"
  4. #include "../server.hpp"
  5. #include "HttpContext.hpp"
  6. class HttpServer
  7. {
  8. private:
  9.     using Handler = std::function<void(const HttpRequest &, HttpResponse *)>;
  10.     using Handlers = std::vector<std::pair<std::regex, Handler>>;
  11.     Handlers _get_route;
  12.     Handlers _post_route;
  13.     Handlers _put_route;
  14.     Handlers _delete_route;
  15.     std::string _basedir; // 静态资源根目录
  16.     TcpServer _server;
  17. private:
  18.     void ErrorHandler(const HttpRequest &req, HttpResponse *rsp)
  19.     {
  20.         // 1. 组织一个错误展示页面
  21.         std::string body;
  22.         body += "<html>";
  23.         body += "<head>";
  24.         body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
  25.         body += "</head>";
  26.         body += "<body>";
  27.         body += "<h1>";
  28.         body += std::to_string(rsp->_statu);
  29.         body += " ";
  30.         body += Util::StatuDesc(rsp->_statu);
  31.         body += "</h1>";
  32.         body += "</body>";
  33.         body += "</html>";
  34.         // 2. 将页面数据,当作响应正文,放入rsp中
  35.         rsp->SetContent(body, "text/html");
  36.     }
  37.     // 将HttpResponse中的要素按照http协议格式进行组织,发送
  38.     void WriteReponse(const PtrConnection &conn, const HttpRequest &req, HttpResponse &rsp)
  39.     {
  40.         // 1. 先完善头部字段
  41.         if (req.Close() == true)
  42.         {
  43.             rsp.SetHeader("Connection", "close");
  44.         }
  45.         else
  46.         {
  47.             rsp.SetHeader("Connection", "keep-alive");
  48.         }
  49.         if (rsp._body.empty() == false && rsp.HasHeader("Content-Length") == false)
  50.         {
  51.             rsp.SetHeader("Content-Length", std::to_string(rsp._body.size()));
  52.         }
  53.         if (rsp._body.empty() == false && rsp.HasHeader("Content-Type") == false)
  54.         {
  55.             rsp.SetHeader("Content-Type", "application/octet-stream");
  56.         }
  57.         if (rsp._redirect_flag == true)
  58.         {
  59.             rsp.SetHeader("Location", rsp._redirect_url);
  60.         }
  61.         // 2. 将rsp中的要素,按照http协议格式进行组织
  62.         std::stringstream rsp_str;
  63.         rsp_str << req._version << " " << std::to_string(rsp._statu) << " " << Util::StatuDesc(rsp._statu) << "\r\n";
  64.         for (auto &head : rsp._headers)
  65.         {
  66.             rsp_str << head.first << ": " << head.second << "\r\n";
  67.         }
  68.         rsp_str << "\r\n";
  69.         rsp_str << rsp._body;
  70.         // 3. 发送数据
  71.         conn->Send(rsp_str.str().c_str(), rsp_str.str().size());
  72.     }
  73.     bool IsFileHandler(const HttpRequest &req)
  74.     {
  75.         // 1. 必须设置了静态资源根目录
  76.         if (_basedir.empty())
  77.         {
  78.             return false;
  79.         }
  80.         // 2. 请求方法,必须是GET / HEAD请求方法
  81.         if (req._method != "GET" && req._method != "HEAD")
  82.         {
  83.             return false;
  84.         }
  85.         // 3. 请求的资源路径必须是一个合法路径
  86.         if (Util::ValidPath(req._path) == false)
  87.         {
  88.             return false;
  89.         }
  90.         std::string req_path = _basedir + req._path; // 为了避免直接修改请求的资源路径,因此定义一个临时对象
  91.         if (req._path.back() == '/')
  92.         {
  93.             req_path += "index.html";
  94.         }
  95.         if (Util::IsRegular(req_path) == false)
  96.         {
  97.             return false;
  98.         }
  99.         return true;
  100.     }
  101.     //静态资源的请求处理 --- 将静态资源文件的数据读取出来,放到rsp的_body中, 并设置mime
  102.     void FileHandler(const HttpRequest &req, HttpResponse *rsp)
  103.     {
  104.         std::string req_path = _basedir + req._path;
  105.         if (req._path.back() == '/')  
  106.         {
  107.             req_path += "index.html";
  108.         }
  109.         bool ret = Util::ReadFile(req_path, &rsp->_body);
  110.         if (ret == false)
  111.         {
  112.             return;
  113.         }
  114.         std::string mime = Util::ExtMime(req_path);
  115.         rsp->SetHeader("Content-Type", mime);
  116.     }
  117.     //功能性请求的分类处理
  118.     void Dispatcher(HttpRequest &req, HttpResponse *rsp, Handlers &handlers)
  119.     {
  120.         //在对应请求方法的路由表中,查找是否含有对应资源请求的处理函数,有则调用,没有则发挥404
  121.         //思想:路由表存储的时键值对 -- 正则表达式 & 处理函数
  122.         //使用正则表达式,对请求的资源路径进行正则匹配,匹配成功就使用对应函数进行处理
  123.         //  /numbers/(\d+)       /numbers/12345
  124.         for(auto& handler : handlers)
  125.         {
  126.             const std::regex &re = handler.first;
  127.             const Handler &functor = handler.second;
  128.             bool ret = std::regex_match(req._path, req._matches, re);
  129.             if (ret == false)
  130.             {
  131.                 continue;
  132.             }
  133.             return functor(req, rsp); // 传入请求信息,和空的rsp,执行处理函数
  134.         }
  135.         rsp->_statu = 404;
  136.     }
  137.     void Route(HttpRequest &req, HttpResponse *rsp)
  138.     {
  139.         //1. 对请求进行分辨,是一个静态资源请求,还是一个功能性请求
  140.         //   静态资源请求,则进行静态资源的处理
  141.         //   功能性请求,则需要通过几个请求路由表来确定是否有处理函数
  142.         //   既不是静态资源请求,也没有设置对应的功能性请求处理函数,就返回405
  143.         if (IsFileHandler(req) == true)
  144.         {
  145.             //是一个静态资源请求, 则进行静态资源请求的处理
  146.             return FileHandler(req, rsp);
  147.         }
  148.         if(req._method == "GET" || req._method == "HEAD")
  149.         {
  150.             return Dispatcher(req, rsp, _get_route);
  151.         }
  152.         else if(req._method == "POST")
  153.         {
  154.             return Dispatcher(req, rsp, _post_route);
  155.         }
  156.         else if(req._method == "PUT")
  157.         {
  158.             return Dispatcher(req, rsp, _put_route);
  159.         }
  160.         else if(req._method == "DELETE")
  161.         {
  162.             return Dispatcher(req, rsp, _delete_route);
  163.         }
  164.         rsp->_statu = 405;// Method Not Allowed
  165.     }
  166.     // 设置上下文
  167.     void OnConnected(const PtrConnection &conn)
  168.     {
  169.         conn->SetContext(HttpContext());
  170.         lg(Info, "NEW CONNECTION %p", conn.get());
  171.     }
  172.     //缓冲区数据解析+处理
  173.     void OnMessage(const PtrConnection &conn, Buffer *buffer)
  174.     {
  175.         while(buffer->ReadAbleSize() > 0)
  176.         {
  177.             // 1. 获取上下文
  178.             HttpContext *context = conn->GetContext()->get<HttpContext>();
  179.             // 2. 通过上下文对缓冲区数据进行解析,得到HttpRequest对象
  180.             //   1. 如果缓冲区的数据解析出错,就直接回复出错响应
  181.             //   2. 如果解析正常,且请求已经获取完毕,才开始去进行处理
  182.             context->RecvHttpRequest(buffer);
  183.             HttpRequest &req = context->Request();
  184.             HttpResponse rsp(context->RespStatu());
  185.             if(context->RespStatu() >= 400)
  186.             {
  187.                 //进行错误响应,关闭连接
  188.                 ErrorHandler(req, &rsp);//填充一个错误显示页面数据到rsp中
  189.                 WriteReponse(conn, req, rsp);//组织响应发送给客户端
  190.                 context->ReSet();
  191.                 buffer->MoveRead(buffer->ReadAbleSize());//出错了就把缓冲区数据清空
  192.                 conn->Shutdown();//关闭连接
  193.                 return;
  194.             }
  195.             if (context->RecvStatu() != RECV_HTTP_OVER)
  196.             {
  197.                 // 当前请求还没有接收完整,则退出,等新数据到来再重新继续处理
  198.                 return;
  199.             }
  200.             // 3. 请求路由 + 业务处理
  201.             Route(req, &rsp);
  202.             // 4. 对HttpResponse进行组织发送
  203.             WriteReponse(conn, req, rsp);
  204.             // 5. 重置上下文
  205.             context->ReSet();
  206.             // 6. 根据长短连接判断是否关闭连接或者继续处理
  207.             if (rsp.Close() == true)
  208.             {
  209.                 conn->Shutdown(); // 短链接则直接关闭v
  210.             }
  211.         }
  212.     }
  213. public:
  214.     HttpServer(int port, int timeout = DEFALT_TIMEOUT)
  215.         :_server(port)
  216.     {
  217.         _server.EnableInactiveRelease(timeout);
  218.         _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected, this, std::placeholders::_1));
  219.         _server.SetMessageCallback(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
  220.     }
  221.     void SetBaseDir(const std::string &path)
  222.     {
  223.         assert(Util::IsDirectory(path) == true);
  224.         _basedir = path;
  225.     }
  226.     //设置/添加,请求(请求的正则表达)与处理函数的映射关系
  227.     void Get(const std::string &pattern, const Handler &handler)
  228.     {
  229.         _get_route.push_back(std::make_pair(std::regex(pattern), handler));
  230.     }
  231.     void Post(const std::string &pattern, const Handler &handler)
  232.     {
  233.         _post_route.push_back(std::make_pair(std::regex(pattern), handler));
  234.     }
  235.     void Put(const std::string &pattern, const Handler &handler)
  236.     {
  237.         _put_route.push_back(std::make_pair(std::regex(pattern), handler));
  238.     }
  239.     void Delete(const std::string &pattern, const Handler &handler)
  240.     {
  241.         _delete_route.push_back(std::make_pair(std::regex(pattern), handler));
  242.     }
  243.     void SetThreadCount(int count)
  244.     {
  245.         _server.SetThreadCount(count);
  246.     }
  247.    
  248.     void Listen()
  249.     {
  250.         _server.Start();
  251.     }
  252. };
复制代码
6. 对服务器团体测试

(1)服务器运行代码:
  1. #include "HttpServer.hpp"
  2. #include "HttpResponse.hpp"
  3. #include "HttpRequest.hpp"
  4. #define WWWROOT "./wwwroot/"
  5. std::string RequestStr(const HttpRequest &req) {
  6.     std::stringstream ss;
  7.     ss << req._method << " " << req._path << " " << req._version << "\r\n";
  8.     for (auto &it : req._params) {
  9.         ss << it.first << ": " << it.second << "\r\n";
  10.     }
  11.     for (auto &it : req._headers) {
  12.         ss << it.first << ": " << it.second << "\r\n";
  13.     }
  14.     ss << "\r\n";
  15.     ss << req._body;
  16.     return ss.str();
  17. }
  18. void Hello(const HttpRequest &req, HttpResponse *rsp)
  19. {
  20.     rsp->SetContent(RequestStr(req), "text/plain");
  21. }
  22. void Login(const HttpRequest &req, HttpResponse *rsp)
  23. {
  24.     rsp->SetContent(RequestStr(req), "text/plain");
  25. }
  26. void PutFile(const HttpRequest &req, HttpResponse *rsp)
  27. {
  28.     std::string pathname = WWWROOT + req._path;
  29.     Util::WriteFile(pathname, req._body);
  30. }
  31. void DelFile(const HttpRequest &req, HttpResponse *rsp)
  32. {
  33.     rsp->SetContent(RequestStr(req), "text/plain");
  34. }
  35. int main()
  36. {
  37.     HttpServer server(8080);
  38.     server.SetThreadCount(3);
  39.     server.SetBaseDir(WWWROOT);//设置静态资源根目录,告诉服务器有静态资源请求到来,需要到哪里去找资源文件
  40.     server.Get("/hello", Hello);
  41.     server.Post("/login", Login);
  42.     server.Put("/1234.txt", PutFile);
  43.     server.Delete("/1234.txt", DelFile);
  44.     server.Listen();
  45.     return 0;
  46. }
复制代码
6.1 长连接测试

(1)客户端代码:
  1. /*长连接测试1: 创建一个客户端持续给服务器发送数据,直到超过时间看是否正常*/
  2. #include "../../server.hpp"
  3. int main()
  4. {
  5.     Sock cli_sock;
  6.     cli_sock.CreateClient(8080, "127.0.0.1");
  7.     std::string req = "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n";
  8.     while (1)
  9.     {
  10.         assert(cli_sock.Send(req.c_str(), req.size()) != -1);
  11.         char buf[1024] = {0};
  12.         assert(cli_sock.Recv(buf, 1023));
  13.         lg(Info, "[%s]", buf);
  14.         sleep(3);
  15.     }
  16.     cli_sock.Close();
  17.     return 0;
  18. }
复制代码
(2)运行结果:

6.2 超时连接测试

(1)客户端代码:
  1. /*超时连接测试1:创建一个客户端,给服务器发送一次数据后,不动了,查看服务器是否会正常的超时关闭连接*/
  2. #include "../../server.hpp"
  3. int main()
  4. {
  5.     Sock cli_sock;
  6.     cli_sock.CreateClient(8080, "127.0.0.1");
  7.     std::string req = "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n";
  8.     while(1) {
  9.         assert(cli_sock.Send(req.c_str(), req.size()) != -1);
  10.         char buf[1024] = {0};
  11.         assert(cli_sock.Recv(buf, 1023));
  12.         lg(Info, "[%s]", buf);
  13.         sleep(15);
  14.     }
  15.     cli_sock.Close();
  16.     return 0;
  17. }
复制代码
(2)运行结果:

6.3 错误请求测试

(1)客户端代码:
  1. /*给服务器发送一个数据,告诉服务器要发送1024字节的数据,但是实际发送的数据不足1024,查看服务器处理结果*/
  2. /*
  3.     1. 如果数据只发送一次,服务器将得不到完整请求,就不会进行业务处理,客户端也就得不到响应,最终超时关闭连接
  4.     2. 连着给服务器发送了多次 小的请求,  服务器会将后边的请求当作前边请求的正文进行处理,而后便处理的时候有可能就会因为处理错误而关闭连接
  5. */
  6. #include "../../server.hpp"
  7. int main()
  8. {
  9.     Sock cli_sock;
  10.     cli_sock.CreateClient(8080, "127.0.0.1");
  11.     std::string req = "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 100\r\n\r\nbitejiuyeke";
  12.     while(1) {
  13.         assert(cli_sock.Send(req.c_str(), req.size()) != -1);
  14.         assert(cli_sock.Send(req.c_str(), req.size()) != -1);
  15.         assert(cli_sock.Send(req.c_str(), req.size()) != -1);
  16.         char buf[1024] = {0};
  17.         assert(cli_sock.Recv(buf, 1023));
  18.         lg(Info, "[%s]", buf);
  19.         sleep(3);
  20.     }
  21.     cli_sock.Close();
  22.     return 0;
  23. }
复制代码
(2)运行结果:

6.4 业务处理超时测试

(1)客户端代码:
  1. /* 业务处理超时,查看服务器的处理情况
  2.     当服务器达到了一个性能瓶颈,在一次业务处理中花费了太长的时间(超过了服务器设置的非活跃超时时间)
  3.      1. 在一次业务处理中耗费太长时间,导致其他的连接也被连累超时,其他的连接有可能会被拖累超时释放
  4.      假设现在  12345描述符就绪了, 在处理1的时候花费了30s处理完,超时了,导致2345描述符因为长时间没有刷新活跃度
  5.        1. 如果接下来的2345描述符都是通信连接描述符,如果都就绪了,则并不影响,因为接下来就会进行处理并刷新活跃度
  6.        2. 如果接下来的2号描述符是定时器事件描述符,定时器触发超时,执行定时任务,就会将345描述符给释放掉
  7.           这时候一旦345描述符对应的连接被释放,接下来在处理345事件的时候就会导致程序崩溃(内存访问错误)
  8.           因此这时候,在本次事件处理中,并不能直接对连接进行释放,而应该将释放操作压入到任务池中,
  9.           等到事件处理完了执行任务池中的任务的时候,再去释放
  10. */
  11. #include "../../server.hpp"
  12. int main()
  13. {
  14.     signal(SIGCHLD, SIG_IGN);
  15.     for (int i = 0; i < 10; i++) {
  16.         pid_t pid = fork();
  17.         if (pid < 0) {
  18.             lg(Fatal, "FORK ERROR");
  19.             return -1;
  20.         }else if (pid == 0) {
  21.             Sock cli_sock;
  22.             cli_sock.CreateClient(8080, "127.0.0.1");
  23.             std::string req = "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n";
  24.             while(1) {
  25.                 assert(cli_sock.Send(req.c_str(), req.size()) != -1);
  26.                 char buf[1024] = {0};
  27.                 assert(cli_sock.Recv(buf, 1023));
  28.                 lg(Info, "[%s]", buf);
  29.             }
  30.             cli_sock.Close();
  31.             exit(0);
  32.         }
  33.     }
  34.     while(1) sleep(1);
  35.    
  36.     return 0;
  37. }
复制代码
(2)服务端修改代码:

(3)运行结果:

6.5 同时多条请求测试

(1)客户端代码:
  1. /*一次性给服务器发送多条数据,然后查看服务器的处理结果*/
  2. /*每一条请求都应该得到正常处理*/
  3. #include "../../server.hpp"
  4. int main()
  5. {
  6.     Sock cli_sock;
  7.     cli_sock.CreateClient(8080, "127.0.0.1");
  8.     std::string req = "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n";
  9.     req += "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n";
  10.     req += "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n";
  11.     while(1) {
  12.         assert(cli_sock.Send(req.c_str(), req.size()) != -1);
  13.         char buf[1024] = {0};
  14.         assert(cli_sock.Recv(buf, 1023));
  15.         lg(Info, "[%s]", buf);
  16.         sleep(3);
  17.     }
  18.     cli_sock.Close();
  19.     return 0;
  20. }
复制代码
(2)运行结果:

6.6 大文件传输测试

(1)客户端代码:
  1. /*大文件传输测试,给服务器上传一个大文件,服务器将文件保存下来,观察处理结果*/
  2. /*
  3.     上传的文件,和服务器保存的文件一致
  4. */
  5. #include "../HttpServer.hpp"
  6. int main()
  7. {
  8.     Sock cli_sock;
  9.     cli_sock.CreateClient(8080, "127.0.0.1");
  10.     std::string req = "PUT /1234.txt HTTP/1.1\r\nConnection: keep-alive\r\n";
  11.     std::string body;
  12.     Util::ReadFile("./hello.txt", &body);
  13.     req += "Content-Length: " + std::to_string(body.size()) + "\r\n\r\n";
  14.     assert(cli_sock.Send(req.c_str(), req.size()) != -1);
  15.     assert(cli_sock.Send(body.c_str(), body.size()) != -1);
  16.     char buf[1024] = {0};
  17.     assert(cli_sock.Recv(buf, 1023));
  18.     lg(Info, "[%s]", buf);
  19.     sleep(3);
  20.     cli_sock.Close();
  21.     return 0;
  22. }
复制代码
(2)运行结果:


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

大连密封材料

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表