IT评测·应用市场-qidao123.com技术社区

标题: 【Linux高级IO(三)】Reactor [打印本页]

作者: 滴水恩情    时间: 2025-4-9 08:59
标题: 【Linux高级IO(三)】Reactor
核心代码
 Epoller.hpp
  1. #pragma once
  2. #include "nocopy.hpp"
  3. #include <cerrno>
  4. #include <sys/epoll.h>
  5. #include <unistd.h>
  6. #include <string.h>
  7. #include "Log.hpp"
  8. class Epoller : public nocopy //类Epoller继承自nocopy类,类Epoller对象不能被拷贝和复值
  9. {
  10.     static const int size = 128;
  11. public:
  12.     Epoller()
  13.     {
  14.         _epfd = epoll_create(size); //创建epoll模型 返回一个文件描述符
  15.         if(_epfd == -1)
  16.         {
  17.             lg(Error,"epoll_create error: %s", strerror(errno));
  18.         }
  19.         else
  20.         {
  21.             lg(Info,"epoll_create success: %d", _epfd);
  22.         }
  23.     }
  24.     int EpollerWait(struct epoll_event revents[], int num, int timeout)  //传一个数组和数组大小就ok
  25.     {
  26.         int n = epoll_wait(_epfd,revents, num, _timeout);//等待epoll实例_epfd上的事件发生,将发生的事件存储在revents数组中,
  27.         //最多存储num个事件 ,超时事件为_timeout毫秒  返回事件发生的数量
  28.         //---解释---第二个参数是指向结构体数组的指针 当检测到有事件发生时,就会将事件的信息:fd、事件类型填充到结构体中
  29.         return n;
  30.     }
  31.     int EpollerUpdate(int oper,int sock,uint32_t event) //修改epoll实例上的文件描述符的监听事件 只需要调用时传递动作和文件描述符 和关心的事件(读、写、错误)
  32.     {
  33.         int n = 0;
  34.         //oper 删
  35.         if(oper == EPOLL_CTL_DEL)
  36.         {
  37.             n = epoll_ctl(_epfd, oper, sock, nullptr);//从epoll实例中删除指定文件描述符sock
  38.             if(n != 0)
  39.             {
  40.                 lg(Error, "epoll_ctl delete error!");
  41.             }
  42.         
  43.         }
  44.         else
  45.         {
  46.             struct epoll_event ev;
  47.             ev.events = event; //关心的事件
  48.             ev.data.fd = sock;
  49.             //oper 增改
  50.             n = epoll_ctl(_epfd,oper,sock,&ev);//通过新增调用 向红黑树中新增节点 让节点和底层队列产生关联
  51.             if(n != 0)
  52.             {
  53.                 lg(Error, "epoll_ctl error!");
  54.             }
  55.         }
  56.         return 0;
  57.     }
  58.     ~Epoller()
  59.     {
  60.         if(_epfd >= 0)
  61.         close(_epfd);
  62.     }
  63. private:
  64.     int _epfd;
  65.     int _timeout{3000};
  66. };
复制代码
 TcpServer.hpp
  1. #pragma once
  2. #include <iostream>
  3. #include <string>
  4. #include <memory>
  5. #include <cerrno>
  6. #include <functional>
  7. #include <unordered_map>
  8. #include "Log.hpp"
  9. #include "nocopy.hpp"
  10. #include "Epoller.hpp"
  11. #include "Socket.hpp"
  12. #include "Comm.hpp"
  13. class Connection;//代表一个客户端的连接,存储与该连接相关的信息与回调函数
  14. class TcpServer;//实现了 TCP 服务器的核心功能,包含监听套接字、epoll 实例以及管理所有连接的映射。
  15. uint32_t EVENT_IN = (EPOLLIN | EPOLLET); //读ET
  16. uint32_t EVENT_OUT = (EPOLLOUT | EPOLLET); //写ET
  17. const static int g_buffer_size = 128;
  18. //func_t表示一个函数对象类型  函数接收一个指向Connection 对象的弱指针std::weak_ptr<Connection> 作为参数
  19. using func_t = std::function<void(std::weak_ptr<Connection>)>;
  20. using except_func = std::function<void(std::weak_ptr<Connection>)>;
  21. class Connection
  22. {
  23. public:
  24.     Connection(int sock) : _sock(sock)
  25.     {
  26.     }
  27.     void SetHandler(func_t recv_cb, func_t send_cb, except_func except_cb)
  28.     {
  29.         _recv_cb = recv_cb;
  30.         _send_cb = send_cb;
  31.         _except_cb = except_cb;
  32.     }
  33.     int SockFd() { return _sock; }
  34.     void AppendInBuffer(const std::string &info)//向输入缓冲区中追加数据
  35.     {
  36.         _inbuffer += info; //传入的字符串追加到输入缓冲区中
  37.     }
  38.     void AppendOutBuffer(const std::string &info)
  39.     {
  40.         _outbuffer += info;
  41.     }
  42.     std::string &Inbuffer() // for debug
  43.     {
  44.         return _inbuffer;//返回输入缓冲区_inbuffer的引用 方便爱不访问和查看输入缓冲区的内容
  45.     }
  46.     std::string &OutBuffer()
  47.     {
  48.         return _outbuffer;
  49.     }
  50.     //设置指向TcpServer对象的弱指针_tcp_server_ptr
  51.     void SetWeakPtr(std::weak_ptr<TcpServer> tcp_server_ptr)
  52.     {
  53.         _tcp_server_ptr = tcp_server_ptr;
  54.     }
  55.     ~Connection()
  56.     {
  57.     }
  58. private:
  59.     int _sock;
  60.     std::string _inbuffer; // string 二进制流,vector
  61.     std::string _outbuffer;
  62. public:
  63.     func_t _recv_cb;//接收回调函数
  64.     func_t _send_cb;//发送回调函数
  65.     except_func _except_cb;//异常处理回调函数
  66.     // 添加一个回指指针
  67.     std::weak_ptr<TcpServer> _tcp_server_ptr; // std::weak_ptr<> // bug??
  68.     // std::shared_ptr<TcpServer> _tcp_server_ptr; // std::weak_ptr<>
  69.     std::string _ip;
  70.     uint16_t _port;
  71. };
  72. // enable_shared_from_this:可以提供返回当前对象的this对应的shared_ptr
  73. class TcpServer : public std::enable_shared_from_this<TcpServer>, public nocopy
  74. {
  75.     static const int num = 64;
  76. public:
  77.     TcpServer(uint16_t port, func_t OnMessage)
  78.         : _port(port),
  79.           _OnMessage(OnMessage),
  80.           _quit(true),
  81.           _epoller_ptr(new Epoller()),
  82.           _listensock_ptr(new Sock())
  83.     {
  84.     }
  85.     void Init() //创建监听套接字 将其设为非阻塞  并将它添加到epoll实例中
  86.     {
  87.         _listensock_ptr->Socket();
  88.         SetNonBlockOrDie(_listensock_ptr->Fd());
  89.         _listensock_ptr->Bind(_port);
  90.         _listensock_ptr->Listen();
  91.         lg(Info, "create listen socket success: %d", _listensock_ptr->Fd());
  92.         
  93.         //将监听套接字添加到epoll中, 设置监听读事件(EVENT_IN)并绑定Accepter函数作为该事件回调函数,同时设置数据发送和异常处理回调函数为nullptr(因为监听套接字主要用于接受连接)
  94.         // ????????????????????????
  95.         //将Accepter函数作为一个回调函数绑定并注册,一般在特定的事件发生时调用,而不是在AddConnection 函数调用时就执行
  96.         //通过 AddConnection 函数将 Accepter 函数作为回调函数注册到监听套接字的 EVENT_IN事件上
  97.         //意味着当有新客户端连接请求到达时,(即监听套接字上发生 EVENT_IN 事件),系统会自动调用Accepter 函数来处理这个新连接
  98.         //获取文件描述符,添加到epoll中,AddConnection并告诉epoll关注它的EVENT_IN 事件
  99.         //AddConnection 函数会将 Accepter 函数作为回调函数与 EVENT_IN 事件绑定。
  100.         //当事件监听机制检测到监听套接字上发生 EVENT_IN 事件时,会调用之前绑定的 Accepter 函数来处理这个新的客户端连接请求。
  101.         AddConnection(_listensock_ptr->Fd(),
  102.                       EVENT_IN, std::bind(&TcpServer::Accepter, this, std::placeholders::_1), nullptr, nullptr);
  103.     }
  104.     //创建新的Connection对象,将其添加到_connections映射中,将对应的事件添加到epoll实例中
  105.     void AddConnection(int sock, uint32_t event, func_t recv_cb, func_t send_cb, except_func except_cb,
  106.                        const std::string &ip = "0.0.0.0", uint16_t port = 0)
  107.     {
  108.         // 1. 给sock也建立一个connection对象,将listensock添加到Connection中,同时,listensock和Connecion放入_connections
  109.         // std::shared_ptr<Connection> new_connection = std::make_shared<Connection>(sock, std::shared_ptr<TcpServer>(this));
  110.         // std::shared_ptr<Connection> new_connection = std::make_shared<Connection>(sock);
  111.         //创建新的Connection对象 new_connection,使用传入的套接字描述符sock进行舒适化 使用new关键字创建并封装为std::shared_ptr
  112.         std::shared_ptr<Connection> new_connection(new Connection(sock));
  113.         new_connection->SetWeakPtr(shared_from_this()); // shared_from_this(): 返回当前对象的shared_ptr //传入当前TcpServer对象的std::shared_ptr  设置指向 TcpServer 的弱指针
  114.         new_connection->SetHandler(recv_cb, send_cb, except_cb);//设置回调函数  把传入的三个回调函数设置到Connection对象中,以便在 ???相应事件????(读、写、异常)发生时调用这些回调函数进行处理
  115.         new_connection->_ip = ip;
  116.         new_connection->_port = port;
  117.         // // 2. 添加到unordered_map
  118.         _connections.insert(std::make_pair(sock, new_connection));
  119.         // // 3. 我们添加对应的事件,除了要加到内核中,fd, event
  120.         _epoller_ptr->EpollerUpdate(EPOLL_CTL_ADD, sock, event);
  121.         // lg(Debug, "add a new connection success, sockfd is : %d", sock);
  122.     }
  123.     // 链接管理器
  124.     //处理新的客户端连接 接受连接并将其添加到epoll实例中
  125.     void Accepter(std::weak_ptr<Connection> conn)
  126.     {
  127.         auto connection = conn.lock();
  128.         while (true)
  129.         {
  130.             struct sockaddr_in peer;
  131.             socklen_t len = sizeof(peer);
  132.             //系统调用accept函数接受一个新的客户端连接 获取监听套接字的文件描述符
  133.             int sock = ::accept(connection->SockFd(), (struct sockaddr *)&peer, &len);
  134.             if (sock > 0) //成功接受了一个新的客户端连接
  135.             {
  136.                 uint16_t peerport = ntohs(peer.sin_port);
  137.                 char ipbuf[128];
  138.                 inet_ntop(AF_INET, &peer.sin_addr.s_addr, ipbuf, sizeof(ipbuf));
  139.                 lg(Debug, "get a new client, get info-> [%s:%d], sockfd : %d", ipbuf, peerport, sock);
  140.                 SetNonBlockOrDie(sock);
  141.                 // listensock只需要设置_recv_cb, 而其他sock,读,写,异常
  142.                 //AddConnection 函数工作---- 创建Connection 对象,设置相关的回调函数,将连接信息存储到 _connections 映射中,
  143.                 //并将套接字和事件添加到 epoll 实例中进行监听
  144.                 AddConnection(sock, EVENT_IN,
  145.                               std::bind(&TcpServer::Recver, this, std::placeholders::_1),
  146.                               //将数据接收的逻辑封装在Recver函数中,使数据接收的处理和Accepter函数的连接接受逻辑分离。这样可以提高代码模块化
  147.                               //&TcpServer::Recver 是TcpServer类里的Recver成员函数 this代表当前TcpServer对象的指针
  148.                               //std::placeholders::_1 是占位符,意味着调用这个绑定函数时会传入一个参数。
  149.                               //当 EVENT_IN 事件触发(即套接字有数据可读)时,AddConnection 函数会调用这个绑定的 Recver 函数来处理接收到的数据。
  150.                               std::bind(&TcpServer::Sender, this, std::placeholders::_1),
  151.                               //当套接字上发生写事件(EPOLLOUT)会调用这个绑定的 Sender 函数。该函数负责将数据从应用程序的输出缓冲区发送到输出缓冲区中
  152.                               std::bind(&TcpServer::Excepter, this, std::placeholders::_1),
  153.                               //当这个套接字上出现异常情况(例如连接断开、网络错误等)时,AddConnection 函数会调用这个绑定的 Excepter 函数来处理异常。
  154.                               ipbuf, peerport); // TODO
  155.             }
  156.             else
  157.             {
  158.                 if (errno == EWOULDBLOCK)
  159.                     break;
  160.                 else if (errno == EINTR)
  161.                     continue;
  162.                 else
  163.                     break;
  164.             }
  165.         }
  166.     }
  167.     // 事件管理器
  168.     // 应不应该关心数据的格式???不应该!!服务器只要IO数据就可以,有没有读完,报文的格式细节,你不用管。
  169.     //处理数据接收,将接收到的数据添加到输入缓冲区,并调用_OnMessage回调函数
  170.     void Recver(std::weak_ptr<Connection> conn) //接收一个指向Connection的弱指针
  171.     {
  172.         if(conn.expired()) return;//检查弱指针是否过期 即所指向的Connection是或否已经被释放 释放就返回 不进行后续操作
  173.         auto connection = conn.lock();//尝试将弱指针 conn 提升为强指针 connection。如果 conn 没有过期,lock 函数会返回一个有效的强指针,否则返回一个空指针。
  174.         
  175.         int sock = connection->SockFd(); //获取当前连接的套接字描述符sock
  176.         while (true) //持续接收数据
  177.         {
  178.             char buffer[g_buffer_size];
  179.             memset(buffer, 0, sizeof(buffer));
  180.             //调用recv系统函数从sock接收数据到buffer中,buffer 大小减 1 个字节的数据(留出一个字节用于存储字符串结束符 \0)
  181.             ssize_t n = recv(sock, buffer, sizeof(buffer) - 1, 0); // 非阻塞读取
  182.             if (n > 0)
  183.             {
  184.                 connection->AppendInBuffer(buffer);//将接收到数据buffer追加到连接的输入缓冲区中
  185.             }
  186.             else if (n == 0)
  187.             {
  188.                 lg(Info, "sockfd: %d, client info %s:%d quit...", sock, connection->_ip.c_str(), connection->_port);
  189.                 connection->_except_cb(connection);
  190.                 return;
  191.             }
  192.             else //小于0 接收数据发生了错误
  193.             {
  194.                 if (errno == EWOULDBLOCK) //错误码是这个表示当前没有数据可读
  195.                     break;
  196.                 else if (errno == EINTR) //是这个表示recv函数被信号中断,继续循环,再次尝试接收数据
  197.                     continue;
  198.                 else
  199.                 {
  200.                     lg(Warning, "sockfd: %d, client info %s:%d recv error...", sock, connection->_ip.c_str(), connection->_port);
  201.                     connection->_except_cb(connection);
  202.                     return;
  203.                 }
  204.             }
  205.         }
  206.         // 数据有了,但是不一定全,1. 检测 2. 如果有完整报文,就处理
  207.         _OnMessage(connection); // 你读到的sock所有的数据connection
  208.     }
  209.     //处理数据发送  将输出缓冲区中的数据发送给客户端,并根据发送情况调整对事件的关注
  210.     void Sender(std::weak_ptr<Connection> conn)
  211.     {
  212.         if(conn.expired()) return;
  213.         auto connection = conn.lock();
  214.         auto &outbuffer = connection->OutBuffer(); //获取连接的输出缓冲区的引用
  215.         while(true)
  216.         {
  217.             //调用send系统函数,将输出缓冲区outbuffer中的数据发送到连接的套接字connection->SockFd()上、获取缓冲区的字符数组表示、要发送的数据长度
  218.             ssize_t n = send(connection->SockFd(), outbuffer.c_str(), outbuffer.size(), 0);
  219.             if(n > 0)
  220.             {
  221.                 outbuffer.erase(0, n); //从发送缓冲区的起始位置删除已经发送的n的字节的数据
  222.                 if(outbuffer.empty()) break;  //缓冲区中数据已经发完 跳出
  223.             }
  224.             else if(n == 0)
  225.             {
  226.                 return;
  227.             }
  228.             else //出现错误
  229.             {
  230.                 if(errno == EWOULDBLOCK) break;
  231.                 else if(errno == EINTR) continue;
  232.                 else{
  233.                     lg(Warning, "sockfd: %d, client info %s:%d send error...", connection->SockFd(), connection->_ip.c_str(), connection->_port);
  234.                     connection->_except_cb(connection);
  235.                     return;
  236.                 }
  237.             }
  238.         }
  239.         
  240.         if(!outbuffer.empty()) //不为空 有未发送的数据
  241.         {
  242.             // 开启对写事件的关心 写
  243.             //----解释----每个套接字(也是一种特殊的文件描述符)都关联两个缓冲区
  244.             //代码中,当要发送的缓冲区不为空时,即还有没发送完的数据的时候
  245.             //我们就要开启对写事件的关心
  246.             //这个写,是写到我们这个套接字对应的发送缓冲区的
  247.             //即当发送缓冲区有空间让我们写的时候,就会通知我们
  248.             //让我们进行写----写到发送缓冲区里面(send函数)
  249.             //一个套接字关注可写其实意味着,可以让应用程序及时了解套接字发送缓冲区的状态,当套接字可写时,epoll会通知程序,程序可以继续调用send函数尝试发送剩余数据
  250.             //如果不开启对些事件的关注,那么即使套接字可写 程序也无法得知,导致数据发不出去
  251.             EnableEvent(connection->SockFd(), true, true);//读、写
  252.         }
  253.         else//已发送完毕
  254.         {
  255.             // 关闭对写事件的关心
  256.             //因为此时没有数据需要发送,即使套接字可写,也不需要程序进行任何操作,
  257.             //关闭写事件的关注可以减少 epoll 的事件通知开销,提高程序的运行效率。
  258.             EnableEvent(connection->SockFd(), true, false);//读、不写
  259.         }
  260.     }
  261.     //处理异常情况,从 epoll 实例中移除异常连接,关闭套接字,并从 _connections 映射中移除该连接。
  262.     void Excepter(std::weak_ptr<Connection> connection)
  263.     {
  264.         if(connection.expired()) return;
  265.         auto conn = connection.lock();
  266.         int fd = conn->SockFd();
  267.         lg(Warning, "Excepter hander sockfd: %d, client info %s:%d excepter handler",
  268.            conn->SockFd(), conn->_ip.c_str(), conn->_port);
  269.         // 1. 移除对特定fd的关心
  270.         // EnableEvent(connection->SockFd(), false, false);
  271.         _epoller_ptr->EpollerUpdate(EPOLL_CTL_DEL, fd, 0);
  272.         // 2. 关闭异常的文件描述符
  273.         lg(Debug, "close %d done...\n", fd);
  274.         close(fd);
  275.         // 3. 从unordered_map中移除
  276.         lg(Debug, "remove %d from _connections...\n", fd);
  277.         // TODO bug
  278.         // auto iter = _connections.find(fd);
  279.         // if(iter == _connections.end()) return;
  280.         // _connections.erase(iter);
  281.         // _connections[fd].reset();
  282.         _connections.erase(fd);
  283.     }
  284.     //调整对指定套接字的读写事件的关注。
  285.     void EnableEvent(int sock, bool readable, bool writeable)
  286.     {
  287.         uint32_t events = 0;
  288.         events |= ((readable ? EPOLLIN : 0) | (writeable ? EPOLLOUT : 0) | EPOLLET);
  289.         _epoller_ptr->EpollerUpdate(EPOLL_CTL_MOD, sock, events);
  290.     }
  291.     //检查指定的套接字是否存在于 _connections 映射中。
  292.     bool IsConnectionSafe(int fd)
  293.     {
  294.         auto iter = _connections.find(fd);
  295.         if (iter == _connections.end()) //走到结尾了 说明没找到
  296.             return false;
  297.         else
  298.             return true;  //找到了
  299.     }
  300.     //处理 epoll_wait 返回的事件,根据事件类型调用相应的回调函数。
  301.     void Dispatcher(int timeout)
  302.     {
  303.         int n = _epoller_ptr->EpollerWait(revs, num, timeout);
  304.         for (int i = 0; i < n; i++)
  305.         {
  306.             uint32_t events = revs[i].events;
  307.             int sock = revs[i].data.fd;
  308.             // 统一把事件异常转换成为读写问题
  309.             // if (events & EPOLLERR)
  310.             //     events |= (EPOLLIN | EPOLLOUT);
  311.             // if (events & EPOLLHUP)
  312.             //     events |= (EPOLLIN | EPOLLOUT);
  313.             // 只需要处理EPOLLIN EPOLLOUT
  314.             if ((events & EPOLLIN) && IsConnectionSafe(sock)) //事件包含读事件、并且文件描述符对应的连接存在于_connections中
  315.             {
  316.                 if (_connections[sock]->_recv_cb)
  317.                     _connections[sock]->_recv_cb(_connections[sock]); //连接的接收回调函数 //????为什么传入这个参数
  318.             }
  319.             if ((events & EPOLLOUT) && IsConnectionSafe(sock))
  320.             {
  321.                 if (_connections[sock]->_send_cb)
  322.                     _connections[sock]->_send_cb(_connections[sock]);
  323.             }
  324.         }
  325.     }
  326.     //服务器的主循环,不断调用 Dispatcher 处理事件。
  327.     void Loop()
  328.     {
  329.         _quit = false; //false服务器开始运行
  330.         // AddConnection();
  331.         while (!_quit)
  332.         {
  333.             // Dispatcher(3000);
  334.             Dispatcher(-1); //等待epoll事件发生 -1表示无限等待
  335.             PrintConnection();
  336.         }
  337.         _quit = true; //结束
  338.     }
  339.     //打印所有连接的套接字描述符和输入缓冲区内容。
  340.     void PrintConnection()
  341.     {
  342.         std::cout << "_connections fd list: ";
  343.         for (auto &connection : _connections)
  344.         {
  345.             std::cout << connection.second->SockFd() << ", ";
  346.             std::cout << "inbuffer: " << connection.second->Inbuffer().c_str();
  347.         }
  348.         std::cout << std::endl;
  349.     }
  350.     ~TcpServer()
  351.     {
  352.     }
  353. private:
  354.     std::shared_ptr<Epoller> _epoller_ptr; // 内核
  355.     std::shared_ptr<Sock> _listensock_ptr; // 监听socket, 可以把他移除到外部
  356.     std::unordered_map<int, std::shared_ptr<Connection>> _connections;//存储所有连接的映射,键位套接字描述符,值位connection对象的智能指针
  357.     struct epoll_event revs[num];
  358.     uint16_t _port;
  359.     bool _quit;
  360.     // 让上层处理信息
  361.     func_t _OnMessage; //一个函数对象 用于处理接收到的消息,
  362. };
复制代码
 Socket.hpp
  1. #pragma once
  2. #include <iostream>
  3. #include <cstring>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <sys/socket.h>
  8. #include <arpa/inet.h>
  9. #include <netinet/in.h>
  10. #include <fcntl.h>
  11. #include "Log.hpp"
  12. //定义四个枚举类型 表示不同的错误类型
  13. enum
  14. {
  15.     SocketErr = 2,
  16.     BindErr,
  17.     ListenErr,
  18.     NON_BOLCK_ERR
  19. };
  20. class Sock
  21. {
  22.     const static int backlog = 20; //等待队列的最大长度
  23. public:
  24.     Sock()
  25.     {
  26.     }
  27.     ~Sock()
  28.     {
  29.     }
  30. public:
  31.     void Socket()
  32.     {
  33.         //调用socket函数创建一个基于IPv4(AF_INET)的TCP(SOCK_STREAM)套接字,并将返回的套接字描述符春初在成员变量sockfd_中
  34.         sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
  35.         if (sockfd_ < 0)
  36.         {
  37.             lg(Fatal, "socker error, %s: %d", strerror(errno), errno);
  38.             exit(SocketErr);
  39.         }
  40.         int opt = 1;
  41.         //调用 setsockopt 函数设置套接字选项,允许地址和端口的重用
  42.         setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
  43.     }
  44.     //将套接字绑定到指定的端口
  45.     void Bind(uint16_t port)
  46.     {
  47.         struct sockaddr_in local; //定义一个sockaddr_in结构体变量local,用于存储本地地址信息
  48.         memset(&local, 0, sizeof(local));//使用 memset 函数将 local 结构体的内容清零。
  49.         local.sin_family = AF_INET; //设置地址族为IPv4
  50.         local.sin_port = htons(port);//端口号从主机字节序转化为网络字节序,并存储在local.sin_port中
  51.         local.sin_addr.s_addr = INADDR_ANY;//设置 IP 地址为任意地址
  52.         //调用bind将socket绑定到指定的地址和端口
  53.         if (bind(sockfd_, (struct sockaddr *)&local, sizeof(local)) < 0)
  54.         {
  55.             lg(Fatal, "bind error, %s: %d", strerror(errno), errno);
  56.             exit(BindErr);
  57.         }
  58.     }
  59.     //将socket设置为监听状态
  60.     void Listen()
  61.     {
  62.         //调用listen函数, 将socket设置为监听状态,backlog 是等待连接队列的最大长度
  63.         if (listen(sockfd_, backlog) < 0)
  64.         {
  65.             lg(Fatal, "listen error, %s: %d", strerror(errno), errno);
  66.             exit(ListenErr);
  67.         }
  68.     }
  69.     //接受客户端的连接请求
  70.     int Accept(std::string *clientip, uint16_t *clientport)
  71.     {
  72.         struct sockaddr_in peer; //定义一个sockaddr_in 结构体变量peer,用于存储客户端的地址信息
  73.         socklen_t len = sizeof(peer);//定义一个len表示peer的结构体长度
  74.         //调用accept函数接受客户端连接请求,返回新的套接字描述符
  75.         int newfd = accept(sockfd_, (struct sockaddr *)&peer, &len);
  76.         if (newfd < 0)
  77.         {
  78.             lg(Warning, "accept error, %s: %d", strerror(errno), errno);
  79.             return -1;
  80.         }
  81.         char ipstr[64];//存储客户端的ip地址字符串
  82.         inet_ntop(AF_INET, &peer.sin_addr, ipstr, sizeof(ipstr));//将客户端的ip地址从二进制转化为字符串形式
  83.         *clientip = ipstr;//将客户端的IP地址存储到clientip指向的字符串中
  84.         *clientport = ntohs(peer.sin_port);//将客户端的端口号从网络字节序转换为主机字节序,并存储到 clientport 指向的变量中。
  85.         return newfd;
  86.     }
  87.     //用于连接到指定的ip地址和端口
  88.     bool Connect(const std::string &ip, const uint16_t &port)
  89.     {
  90.         struct sockaddr_in peer;//存储目标地址信息
  91.         memset(&peer, 0, sizeof(peer));//清零
  92.         peer.sin_family = AF_INET;//设置地址族为 IPv4。
  93.         peer.sin_port = htons(port);//将端口号从主机字节序转换为网络字节序。
  94.         inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));//调用 inet_pton 函数将 IP 地址从字符串形式转换为二进制形式。
  95.         //调用 connect 函数连接到指定的地址和端口,返回值存储在 n 中
  96.         int n = connect(sockfd_, (struct sockaddr*)&peer, sizeof(peer));
  97.         if(n == -1)
  98.         {
  99.             std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
  100.             return false;
  101.         }
  102.         return true;
  103.     }
  104.     void Close()
  105.     {
  106.         close(sockfd_);
  107.     }
  108.     int Fd()
  109.     {
  110.         return sockfd_;
  111.     }
  112.   
  113. private:
  114.     int sockfd_;
  115. };
复制代码
  1. void Init() //创建监听套接字 将其设为非阻塞  并将它添加到epoll实例中
  2.     {
  3.         _listensock_ptr->Socket();
  4.         SetNonBlockOrDie(_listensock_ptr->Fd());
  5.         _listensock_ptr->Bind(_port);
  6.         _listensock_ptr->Listen();
  7.         lg(Info, "create listen socket success: %d", _listensock_ptr->Fd());
  8.         
  9.         //将监听套接字添加到epoll中, 设置监听读事件(EVENT_IN)并绑定Accepter函数作为该事件回调函数,同时设置数据发送和异常处理回调函数为nullptr(因为监听套接字主要用于接受连接)
  10.         // ????????????????????????
  11.         //将Accepter函数作为一个回调函数绑定并注册,一般在特定的事件发生时调用,而不是在AddConnection 函数调用时就执行
  12.         //通过 AddConnection 函数将 Accepter 函数作为回调函数注册到监听套接字的 EVENT_IN事件上
  13.         //意味着当有新客户端连接请求到达时,(即监听套接字上发生 EVENT_IN 事件),系统会自动调用Accepter 函数来处理这个新连接
  14.         //获取文件描述符,添加到epoll中,AddConnection并告诉epoll关注它的EVENT_IN 事件
  15.         //AddConnection 函数会将 Accepter 函数作为回调函数与 EVENT_IN 事件绑定。
  16.         //当事件监听机制检测到监听套接字上发生 EVENT_IN 事件时,会调用之前绑定的 Accepter 函数来处理这个新的客户端连接请求。
  17.         AddConnection(_listensock_ptr->Fd(),
  18.                       EVENT_IN, std::bind(&TcpServer::Accepter, this, std::placeholders::_1), nullptr, nullptr);
  19.     }
复制代码
  为什么要在初始化的时候调用AddConnection函数??
1、服务器在启动的时候需要创建一个监听套接字,用于监听客户端的连接哀求。通过调用
Addconnection 函数,将监听套接字的文件描述符(_listensock_ptr->Fd())添加到 epoll 实例中,并指定要监听的事件为读事件(EVENT_IN)。这样,epol1就会一连关注该监听套接字,一旦有新的客户端连接哀求到达,就会触发EVENT_IN事件。
  2、绑定回调:在AddConnection 函数调用中,将 Accepter 函数作为回调函数与EVENT_IN 事件绑定。当 epoll 检测到监听套接字上发生 EVENT_IN 事件时,会主动调用 Accepter 函数来处理新的客户端连接哀求。Accepter 函数负责担当新连接、设置新连接的属性(如设置为非阻塞模式)以及为新连接添加到服务器的连接管理体系中。
  3、可能会有大量的客户端同时实验连接服务器。通过在初始化时将监听套接字添加到 epoll 中并绑定 Accepter 回调函数,服务器可以高效地处理这些连接哀求,而不会因为某个连接哀求的处理而阻塞其他连接的担当。
  
  实现异步事件驱动模型
  在网络编程中,通常接纳异步事件驱动模型来处理多个客户端连接,以提高服务器的并发处理能力。监听套接字(_listensock_ptr->Fd())的紧张作用是等待新的客户端连接哀求。通过 AddConnection 函数将 Accepter 函数作为回调函数注册到监听套接字的 EVENT_IN 事件上,意味着当有新的客户端连接哀求到达时(即监听套接字上发生 EVENT_IN 事件),体系会主动调用 Accepter 函数来处理这个新连接。
   这种方式避免了服务器不停阻塞在等待新连接的操作上,服务器可以在等待新连接的同时处理其他任务,提高了资源利用率和程序的响应速度。比方,在一个多用户在线游戏服务器中,服务器可以在等待新玩家连接的同时处理现有玩家的游戏操作
  
  分离连接担当和事件管理逻辑
  将 Accepter 函数作为回调函数注册,实现了连接担当逻辑和事件管理逻辑的分离。AddConnection 函数紧张负责将套接字添加到事件监听机制中,并为不同的事件范例注册相应的回调函数,它专注于事件的管理和调度。而 Accepter 函数则专注于处理新的客户端连接,包括担当连接、创建新的套接字、设置新连接的属性等操作。
   这种分离使得代码结构更加清晰,易于维护和扩展。假如需要修改连接担当的逻辑,只需要修改 Accepter 函数;假如需要调整事件管理的方式,只需要修改 AddConnection 函数或相关的事件处理机制。
  
  提高代码的可复用性和机动性
  将 Accepter 函数作为回调函数注册,使得代码具有更高的可复用性和机动性。Accepter 函数可以被多个不同的监听套接字复用,只要这些套接字需要处理新的客户端连接。同时,假如需要更换连接担当的处理方式,只需要提供一个新的回调函数并注册到 AddConnection 函数中即可,而不需要修改 AddConnection 函数的实现。
   比方,在不同的网络应用场景中,可能需要不同的连接担当计谋,如限制最大连接数、举行身份验证等。通过更换回调函数,可以轻松实现这些不同的计谋,而不会影响到事件管理的核心逻辑。

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




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4