├── CGImysql ├── README.md ├── sql_connection_pool.cpp └── sql_connection_pool.h ├── LICENSE ├── README.md ├── build.sh ├── config.cpp ├── config.h ├── http ├── README.md ├── http_conn.cpp └── http_conn.h ├── lock ├── README.md └── locker.h ├── log ├── README.md ├── block_queue.h ├── log.cpp └── log.h ├── main.cpp ├── makefile ├── root ├── README.md ├── fans.html ├── favicon.ico ├── frame.jpg ├── judge.html ├── log.html ├── logError.html ├── login.gif ├── loginnew.gif ├── picture.gif ├── picture.html ├── register.gif ├── register.html ├── registerError.html ├── registernew.gif ├── test1.jpg ├── video.gif ├── video.html ├── welcome.html ├── xxx.jpg └── xxx.mp4 ├── test_presure ├── README.md └── webbench-1.5 │ ├── COPYRIGHT │ ├── ChangeLog │ ├── Makefile │ ├── debian │ ├── changelog │ ├── control │ ├── copyright │ ├── dirs │ └── rules │ ├── socket.c │ ├── tags │ ├── webbench │ ├── webbench.1 │ ├── webbench.c │ └── webbench.o ├── threadpool ├── README.md └── threadpool.h ├── timer ├── README.md ├── lst_timer.cpp └── lst_timer.h ├── webserver.cpp └── webserver.h /CGImysql/README.md: -------------------------------------------------------------------------------- 1 | 2 | 校验 & 数据库连接池 3 | =============== 4 | 数据库连接池 5 | > * 单例模式,保证唯一 6 | > * list实现连接池 7 | > * 连接池为静态大小 8 | > * 互斥锁实现线程安全 9 | 10 | 校验 11 | > * HTTP请求采用POST方式 12 | > * 登录用户名和密码校验 13 | > * 用户注册及多线程注册安全 14 | -------------------------------------------------------------------------------- /CGImysql/sql_connection_pool.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "sql_connection_pool.h" 10 | 11 | using namespace std; 12 | 13 | connection_pool::connection_pool() 14 | { 15 | m_CurConn = 0; 16 | m_FreeConn = 0; 17 | } 18 | 19 | connection_pool *connection_pool::GetInstance() 20 | { 21 | static connection_pool connPool; 22 | return &connPool; 23 | } 24 | 25 | //构造初始化 26 | void connection_pool::init(string url, string User, string PassWord, string DBName, int Port, int MaxConn, int close_log) 27 | { 28 | m_url = url; 29 | m_Port = Port; 30 | m_User = User; 31 | m_PassWord = PassWord; 32 | m_DatabaseName = DBName; 33 | m_close_log = close_log; 34 | 35 | for (int i = 0; i < MaxConn; i++) 36 | { 37 | MYSQL *con = NULL; 38 | con = mysql_init(con); 39 | 40 | if (con == NULL) 41 | { 42 | LOG_ERROR("MySQL Error"); 43 | exit(1); 44 | } 45 | con = mysql_real_connect(con, url.c_str(), User.c_str(), PassWord.c_str(), DBName.c_str(), Port, NULL, 0); 46 | 47 | if (con == NULL) 48 | { 49 | LOG_ERROR("MySQL Error"); 50 | exit(1); 51 | } 52 | connList.push_back(con); 53 | ++m_FreeConn; 54 | } 55 | 56 | reserve = sem(m_FreeConn); 57 | 58 | m_MaxConn = m_FreeConn; 59 | } 60 | 61 | 62 | //当有请求时,从数据库连接池中返回一个可用连接,更新使用和空闲连接数 63 | MYSQL *connection_pool::GetConnection() 64 | { 65 | MYSQL *con = NULL; 66 | 67 | if (0 == connList.size()) 68 | return NULL; 69 | 70 | reserve.wait(); 71 | 72 | lock.lock(); 73 | 74 | con = connList.front(); 75 | connList.pop_front(); 76 | 77 | --m_FreeConn; 78 | ++m_CurConn; 79 | 80 | lock.unlock(); 81 | return con; 82 | } 83 | 84 | //释放当前使用的连接 85 | bool connection_pool::ReleaseConnection(MYSQL *con) 86 | { 87 | if (NULL == con) 88 | return false; 89 | 90 | lock.lock(); 91 | 92 | connList.push_back(con); 93 | ++m_FreeConn; 94 | --m_CurConn; 95 | 96 | lock.unlock(); 97 | 98 | reserve.post(); 99 | return true; 100 | } 101 | 102 | //销毁数据库连接池 103 | void connection_pool::DestroyPool() 104 | { 105 | 106 | lock.lock(); 107 | if (connList.size() > 0) 108 | { 109 | list::iterator it; 110 | for (it = connList.begin(); it != connList.end(); ++it) 111 | { 112 | MYSQL *con = *it; 113 | mysql_close(con); 114 | } 115 | m_CurConn = 0; 116 | m_FreeConn = 0; 117 | connList.clear(); 118 | } 119 | 120 | lock.unlock(); 121 | } 122 | 123 | //当前空闲的连接数 124 | int connection_pool::GetFreeConn() 125 | { 126 | return this->m_FreeConn; 127 | } 128 | 129 | connection_pool::~connection_pool() 130 | { 131 | DestroyPool(); 132 | } 133 | 134 | connectionRAII::connectionRAII(MYSQL **SQL, connection_pool *connPool){ 135 | *SQL = connPool->GetConnection(); 136 | 137 | conRAII = *SQL; 138 | poolRAII = connPool; 139 | } 140 | 141 | connectionRAII::~connectionRAII(){ 142 | poolRAII->ReleaseConnection(conRAII); 143 | } -------------------------------------------------------------------------------- /CGImysql/sql_connection_pool.h: -------------------------------------------------------------------------------- 1 | #ifndef _CONNECTION_POOL_ 2 | #define _CONNECTION_POOL_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include "../lock/locker.h" 12 | #include "../log/log.h" 13 | 14 | using namespace std; 15 | 16 | class connection_pool 17 | { 18 | public: 19 | MYSQL *GetConnection(); //获取数据库连接 20 | bool ReleaseConnection(MYSQL *conn); //释放连接 21 | int GetFreeConn(); //获取连接 22 | void DestroyPool(); //销毁所有连接 23 | 24 | //单例模式 25 | static connection_pool *GetInstance(); 26 | 27 | void init(string url, string User, string PassWord, string DataBaseName, int Port, int MaxConn, int close_log); 28 | 29 | private: 30 | connection_pool(); 31 | ~connection_pool(); 32 | 33 | int m_MaxConn; //最大连接数 34 | int m_CurConn; //当前已使用的连接数 35 | int m_FreeConn; //当前空闲的连接数 36 | locker lock; 37 | list connList; //连接池 38 | sem reserve; 39 | 40 | public: 41 | string m_url; //主机地址 42 | string m_Port; //数据库端口号 43 | string m_User; //登陆数据库用户名 44 | string m_PassWord; //登陆数据库密码 45 | string m_DatabaseName; //使用数据库名 46 | int m_close_log; //日志开关 47 | }; 48 | 49 | class connectionRAII{ 50 | 51 | public: 52 | connectionRAII(MYSQL **con, connection_pool *connPool); 53 | ~connectionRAII(); 54 | 55 | private: 56 | MYSQL *conRAII; 57 | connection_pool *poolRAII; 58 | }; 59 | 60 | #endif 61 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | TinyWebServer 4 | =============== 5 | Linux下C++轻量级Web服务器,助力初学者快速实践网络编程,搭建属于自己的服务器. 6 | 7 | * 使用 **线程池 + 非阻塞socket + epoll(ET和LT均实现) + 事件处理(Reactor和模拟Proactor均实现)** 的并发模型 8 | * 使用**状态机**解析HTTP请求报文,支持解析**GET和POST**请求 9 | * 访问服务器数据库实现web端用户**注册、登录**功能,可以请求服务器**图片和视频文件** 10 | * 实现**同步/异步日志系统**,记录服务器运行状态 11 | * 经Webbench压力测试可以实现**上万的并发连接**数据交换 12 | 13 | 目录 14 | ----- 15 | 16 | | [概述](#概述) | [框架](#框架) | [Demo演示](#Demo演示) | [压力测试](#压力测试) |[更新日志](#更新日志) |[源码下载](#源码下载) | [快速运行](#快速运行) | [个性化运行](#个性化运行) | [庖丁解牛](#庖丁解牛) | [CPP11实现](#CPP11实现) |[致谢](#致谢) | 17 | |:--------:|:--------:|:--------:|:--------:|:--------:|:--------:|:--------:|:--------:|:--------:|:--------:|:--------:| 18 | 19 | 20 | 概述 21 | ---------- 22 | 23 | > * C/C++ 24 | > * B/S模型 25 | > * [线程同步机制包装类](https://github.com/qinguoyi/TinyWebServer/tree/master/lock) 26 | > * [http连接请求处理类](https://github.com/qinguoyi/TinyWebServer/tree/master/http) 27 | > * [半同步/半反应堆线程池](https://github.com/qinguoyi/TinyWebServer/tree/master/threadpool) 28 | > * [定时器处理非活动连接](https://github.com/qinguoyi/TinyWebServer/tree/master/timer) 29 | > * [同步/异步日志系统 ](https://github.com/qinguoyi/TinyWebServer/tree/master/log) 30 | > * [数据库连接池](https://github.com/qinguoyi/TinyWebServer/tree/master/CGImysql) 31 | > * [同步线程注册和登录校验](https://github.com/qinguoyi/TinyWebServer/tree/master/CGImysql) 32 | > * [简易服务器压力测试](https://github.com/qinguoyi/TinyWebServer/tree/master/test_presure) 33 | 34 | 35 | 框架 36 | ------------- 37 |
38 | 39 | Demo演示 40 | ---------- 41 | > * 注册演示 42 | 43 |
44 | 45 | > * 登录演示 46 | 47 |
48 | 49 | > * 请求图片文件演示(6M) 50 | 51 |
52 | 53 | > * 请求视频文件演示(39M) 54 | 55 |
56 | 57 | 58 | 压力测试 59 | ------------- 60 | 在关闭日志后,使用Webbench对服务器进行压力测试,对listenfd和connfd分别采用ET和LT模式,均可实现上万的并发连接,下面列出的是两者组合后的测试结果. 61 | 62 | > * Proactor,LT + LT,93251 QPS 63 | 64 |
65 | 66 | > * Proactor,LT + ET,97459 QPS 67 | 68 |
69 | 70 | > * Proactor,ET + LT,80498 QPS 71 | 72 |
73 | 74 | > * Proactor,ET + ET,92167 QPS 75 | 76 |
77 | 78 | > * Reactor,LT + ET,69175 QPS 79 | 80 |
81 | 82 | > * 并发连接总数:10500 83 | > * 访问服务器时间:5s 84 | > * 所有访问均成功 85 | 86 | **注意:** 使用本项目的webbench进行压测时,若报错显示webbench命令找不到,将可执行文件webbench删除后,重新编译即可。 87 | 88 | 更新日志 89 | ------- 90 | - [x] 解决请求服务器上大文件的Bug 91 | - [x] 增加请求视频文件的页面 92 | - [x] 解决数据库同步校验内存泄漏 93 | - [x] 实现非阻塞模式下的ET和LT触发,并完成压力测试 94 | - [x] 完善`lock.h`中的封装类,统一使用该同步机制 95 | - [x] 改进代码结构,更新局部变量懒汉单例模式 96 | - [x] 优化数据库连接池信号量与代码结构 97 | - [x] 使用RAII机制优化数据库连接的获取与释放 98 | - [x] 优化代码结构,封装工具类以减少全局变量 99 | - [x] 编译一次即可,命令行进行个性化测试更加友好 100 | - [x] main函数封装重构 101 | - [x] 新增命令行日志开关,关闭日志后更新压力测试结果 102 | - [x] 改进编译方式,只配置一次SQL信息即可 103 | - [x] 新增Reactor模式,并完成压力测试 104 | 105 | 源码下载 106 | ------- 107 | 目前有两个版本,版本间的代码结构有较大改动,文档和代码运行方法也不一致。重构版本更简洁,原始版本(raw_version)更大保留游双代码的原汁原味,从原始版本更容易入手. 108 | 109 | 如果遇到github代码下载失败,或访问太慢,可以从以下链接下载,与Github最新提交同步. 110 | 111 | * 重构版本下载地址 : [BaiduYun](https://pan.baidu.com/s/1PozKji8Oop-1BYcfixZR0g) 112 | * 提取码 : vsqq 113 | * 原始版本(raw_version)下载地址 : [BaiduYun](https://pan.baidu.com/s/1asMNDW-zog92DZY1Oa4kaQ) 114 | * 提取码 : 9wye 115 | * 原始版本运行请参考[原始文档](https://github.com/qinguoyi/TinyWebServer/tree/raw_version) 116 | 117 | 快速运行 118 | ------------ 119 | * 服务器测试环境 120 | * Ubuntu版本16.04 121 | * MySQL版本5.7.29 122 | * 浏览器测试环境 123 | * Windows、Linux均可 124 | * Chrome 125 | * FireFox 126 | * 其他浏览器暂无测试 127 | 128 | * 测试前确认已安装MySQL数据库 129 | 130 | ```C++ 131 | // 建立yourdb库 132 | create database yourdb; 133 | 134 | // 创建user表 135 | USE yourdb; 136 | CREATE TABLE user( 137 | username char(50) NULL, 138 | passwd char(50) NULL 139 | )ENGINE=InnoDB; 140 | 141 | // 添加数据 142 | INSERT INTO user(username, passwd) VALUES('name', 'passwd'); 143 | ``` 144 | 145 | * 修改main.cpp中的数据库初始化信息 146 | 147 | ```C++ 148 | //数据库登录名,密码,库名 149 | string user = "root"; 150 | string passwd = "root"; 151 | string databasename = "yourdb"; 152 | ``` 153 | 154 | * build 155 | 156 | ```C++ 157 | sh ./build.sh 158 | ``` 159 | 160 | * 启动server 161 | 162 | ```C++ 163 | ./server 164 | ``` 165 | 166 | * 浏览器端 167 | 168 | ```C++ 169 | ip:9006 170 | ``` 171 | 172 | 个性化运行 173 | ------ 174 | 175 | ```C++ 176 | ./server [-p port] [-l LOGWrite] [-m TRIGMode] [-o OPT_LINGER] [-s sql_num] [-t thread_num] [-c close_log] [-a actor_model] 177 | ``` 178 | 179 | 温馨提示:以上参数不是非必须,不用全部使用,根据个人情况搭配选用即可. 180 | 181 | * -p,自定义端口号 182 | * 默认9006 183 | * -l,选择日志写入方式,默认同步写入 184 | * 0,同步写入 185 | * 1,异步写入 186 | * -m,listenfd和connfd的模式组合,默认使用LT + LT 187 | * 0,表示使用LT + LT 188 | * 1,表示使用LT + ET 189 | * 2,表示使用ET + LT 190 | * 3,表示使用ET + ET 191 | * -o,优雅关闭连接,默认不使用 192 | * 0,不使用 193 | * 1,使用 194 | * -s,数据库连接数量 195 | * 默认为8 196 | * -t,线程数量 197 | * 默认为8 198 | * -c,关闭日志,默认打开 199 | * 0,打开日志 200 | * 1,关闭日志 201 | * -a,选择反应堆模型,默认Proactor 202 | * 0,Proactor模型 203 | * 1,Reactor模型 204 | 205 | 测试示例命令与含义 206 | 207 | ```C++ 208 | ./server -p 9007 -l 1 -m 0 -o 1 -s 10 -t 10 -c 1 -a 1 209 | ``` 210 | 211 | - [x] 端口9007 212 | - [x] 异步写入日志 213 | - [x] 使用LT + LT组合 214 | - [x] 使用优雅关闭连接 215 | - [x] 数据库连接池内有10条连接 216 | - [x] 线程池内有10条线程 217 | - [x] 关闭日志 218 | - [x] Reactor反应堆模型 219 | 220 | 庖丁解牛 221 | ------------ 222 | 近期版本迭代较快,以下内容多以旧版本(raw_version)代码为蓝本进行详解. 223 | 224 | * [小白视角:一文读懂社长的TinyWebServer](https://huixxi.github.io/2020/06/02/%E5%B0%8F%E7%99%BD%E8%A7%86%E8%A7%92%EF%BC%9A%E4%B8%80%E6%96%87%E8%AF%BB%E6%87%82%E7%A4%BE%E9%95%BF%E7%9A%84TinyWebServer/#more) 225 | * [最新版Web服务器项目详解 - 01 线程同步机制封装类](https://mp.weixin.qq.com/s?__biz=MzAxNzU2MzcwMw==&mid=2649274278&idx=3&sn=5840ff698e3f963c7855d702e842ec47&chksm=83ffbefeb48837e86fed9754986bca6db364a6fe2e2923549a378e8e5dec6e3cf732cdb198e2&scene=0&xtrack=1#rd) 226 | * [最新版Web服务器项目详解 - 02 半同步半反应堆线程池(上)](https://mp.weixin.qq.com/s?__biz=MzAxNzU2MzcwMw==&mid=2649274278&idx=4&sn=caa323faf0c51d882453c0e0c6a62282&chksm=83ffbefeb48837e841a6dbff292217475d9075e91cbe14042ad6e55b87437dcd01e6d9219e7d&scene=0&xtrack=1#rd) 227 | * [最新版Web服务器项目详解 - 03 半同步半反应堆线程池(下)](https://mp.weixin.qq.com/s/PB8vMwi8sB4Jw3WzAKpWOQ) 228 | * [最新版Web服务器项目详解 - 04 http连接处理(上)](https://mp.weixin.qq.com/s/BfnNl-3jc_x5WPrWEJGdzQ) 229 | * [最新版Web服务器项目详解 - 05 http连接处理(中)](https://mp.weixin.qq.com/s/wAQHU-QZiRt1VACMZZjNlw) 230 | * [最新版Web服务器项目详解 - 06 http连接处理(下)](https://mp.weixin.qq.com/s/451xNaSFHxcxfKlPBV3OCg) 231 | * [最新版Web服务器项目详解 - 07 定时器处理非活动连接(上)](https://mp.weixin.qq.com/s/mmXLqh_NywhBXJvI45hchA) 232 | * [最新版Web服务器项目详解 - 08 定时器处理非活动连接(下)](https://mp.weixin.qq.com/s/fb_OUnlV1SGuOUdrGrzVgg) 233 | * [最新版Web服务器项目详解 - 09 日志系统(上)](https://mp.weixin.qq.com/s/IWAlPzVDkR2ZRI5iirEfCg) 234 | * [最新版Web服务器项目详解 - 10 日志系统(下)](https://mp.weixin.qq.com/s/f-ujwFyCe1LZa3EB561ehA) 235 | * [最新版Web服务器项目详解 - 11 数据库连接池](https://mp.weixin.qq.com/s?__biz=MzAxNzU2MzcwMw==&mid=2649274326&idx=1&sn=5af78e2bf6552c46ae9ab2aa22faf839&chksm=83ffbe8eb4883798c3abb82ddd124c8100a39ef41ab8d04abe42d344067d5e1ac1b0cac9d9a3&token=1450918099&lang=zh_CN#rd) 236 | * [最新版Web服务器项目详解 - 12 注册登录](https://mp.weixin.qq.com/s?__biz=MzAxNzU2MzcwMw==&mid=2649274431&idx=4&sn=7595a70f06a79cb7abaebcd939e0cbee&chksm=83ffb167b4883871ce110aeb23e04acf835ef41016517247263a2c3ab6f8e615607858127ea6&token=1686112912&lang=zh_CN#rd) 237 | * [最新版Web服务器项目详解 - 13 踩坑与面试题](https://mp.weixin.qq.com/s?__biz=MzAxNzU2MzcwMw==&mid=2649274431&idx=1&sn=2dd28c92f5d9704a57c001a3d2630b69&chksm=83ffb167b48838715810b27b8f8b9a576023ee5c08a8e5d91df5baf396732de51268d1bf2a4e&token=1686112912&lang=zh_CN#rd) 238 | * 已更新完毕 239 | 240 | CPP11实现 241 | ------------ 242 | 更简洁,更优雅的CPP11实现:[Webserver](https://github.com/markparticle/WebServer) 243 | 244 | 致谢 245 | ------------ 246 | Linux高性能服务器编程,游双著. 247 | 248 | 感谢以下朋友的PR和帮助: [@RownH](https://github.com/RownH),[@mapleFU](https://github.com/mapleFU),[@ZWiley](https://github.com/ZWiley),[@zjuHong](https://github.com/zjuHong),[@mamil](https://github.com/mamil),[@byfate](https://github.com/byfate),[@MaJun827](https://github.com/MaJun827),[@BBLiu-coder](https://github.com/BBLiu-coder),[@smoky96](https://github.com/smoky96),[@yfBong](https://github.com/yfBong),[@liuwuyao](https://github.com/liuwuyao),[@Huixxi](https://github.com/Huixxi),[@markparticle](https://github.com/markparticle). 249 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | make server -------------------------------------------------------------------------------- /config.cpp: -------------------------------------------------------------------------------- 1 | #include "config.h" 2 | 3 | Config::Config(){ 4 | //端口号,默认9006 5 | PORT = 9006; 6 | 7 | //日志写入方式,默认同步 8 | LOGWrite = 0; 9 | 10 | //触发组合模式,默认listenfd LT + connfd LT 11 | TRIGMode = 0; 12 | 13 | //listenfd触发模式,默认LT 14 | LISTENTrigmode = 0; 15 | 16 | //connfd触发模式,默认LT 17 | CONNTrigmode = 0; 18 | 19 | //优雅关闭链接,默认不使用 20 | OPT_LINGER = 0; 21 | 22 | //数据库连接池数量,默认8 23 | sql_num = 8; 24 | 25 | //线程池内的线程数量,默认8 26 | thread_num = 8; 27 | 28 | //关闭日志,默认不关闭 29 | close_log = 0; 30 | 31 | //并发模型,默认是proactor 32 | actor_model = 0; 33 | } 34 | 35 | void Config::parse_arg(int argc, char*argv[]){ 36 | int opt; 37 | const char *str = "p:l:m:o:s:t:c:a:"; 38 | while ((opt = getopt(argc, argv, str)) != -1) 39 | { 40 | switch (opt) 41 | { 42 | case 'p': 43 | { 44 | PORT = atoi(optarg); 45 | break; 46 | } 47 | case 'l': 48 | { 49 | LOGWrite = atoi(optarg); 50 | break; 51 | } 52 | case 'm': 53 | { 54 | TRIGMode = atoi(optarg); 55 | break; 56 | } 57 | case 'o': 58 | { 59 | OPT_LINGER = atoi(optarg); 60 | break; 61 | } 62 | case 's': 63 | { 64 | sql_num = atoi(optarg); 65 | break; 66 | } 67 | case 't': 68 | { 69 | thread_num = atoi(optarg); 70 | break; 71 | } 72 | case 'c': 73 | { 74 | close_log = atoi(optarg); 75 | break; 76 | } 77 | case 'a': 78 | { 79 | actor_model = atoi(optarg); 80 | break; 81 | } 82 | default: 83 | break; 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /config.h: -------------------------------------------------------------------------------- 1 | #ifndef CONFIG_H 2 | #define CONFIG_H 3 | 4 | #include "webserver.h" 5 | 6 | using namespace std; 7 | 8 | class Config 9 | { 10 | public: 11 | Config(); 12 | ~Config(){}; 13 | 14 | void parse_arg(int argc, char*argv[]); 15 | 16 | //端口号 17 | int PORT; 18 | 19 | //日志写入方式 20 | int LOGWrite; 21 | 22 | //触发组合模式 23 | int TRIGMode; 24 | 25 | //listenfd触发模式 26 | int LISTENTrigmode; 27 | 28 | //connfd触发模式 29 | int CONNTrigmode; 30 | 31 | //优雅关闭链接 32 | int OPT_LINGER; 33 | 34 | //数据库连接池数量 35 | int sql_num; 36 | 37 | //线程池内的线程数量 38 | int thread_num; 39 | 40 | //是否关闭日志 41 | int close_log; 42 | 43 | //并发模型选择 44 | int actor_model; 45 | }; 46 | 47 | #endif -------------------------------------------------------------------------------- /http/README.md: -------------------------------------------------------------------------------- 1 | 2 | http连接处理类 3 | =============== 4 | 根据状态转移,通过主从状态机封装了http连接类。其中,主状态机在内部调用从状态机,从状态机将处理状态和数据传给主状态机 5 | > * 客户端发出http连接请求 6 | > * 从状态机读取数据,更新自身状态和接收数据,传给主状态机 7 | > * 主状态机根据从状态机状态,更新自身状态,决定响应请求还是继续读取 -------------------------------------------------------------------------------- /http/http_conn.cpp: -------------------------------------------------------------------------------- 1 | #include "http_conn.h" 2 | 3 | #include 4 | #include 5 | 6 | //定义http响应的一些状态信息 7 | const char *ok_200_title = "OK"; 8 | const char *error_400_title = "Bad Request"; 9 | const char *error_400_form = "Your request has bad syntax or is inherently impossible to staisfy.\n"; 10 | const char *error_403_title = "Forbidden"; 11 | const char *error_403_form = "You do not have permission to get file form this server.\n"; 12 | const char *error_404_title = "Not Found"; 13 | const char *error_404_form = "The requested file was not found on this server.\n"; 14 | const char *error_500_title = "Internal Error"; 15 | const char *error_500_form = "There was an unusual problem serving the request file.\n"; 16 | 17 | locker m_lock; 18 | map users; 19 | 20 | void http_conn::initmysql_result(connection_pool *connPool) 21 | { 22 | //先从连接池中取一个连接 23 | MYSQL *mysql = NULL; 24 | connectionRAII mysqlcon(&mysql, connPool); 25 | 26 | //在user表中检索username,passwd数据,浏览器端输入 27 | if (mysql_query(mysql, "SELECT username,passwd FROM user")) 28 | { 29 | LOG_ERROR("SELECT error:%s\n", mysql_error(mysql)); 30 | } 31 | 32 | //从表中检索完整的结果集 33 | MYSQL_RES *result = mysql_store_result(mysql); 34 | 35 | //返回结果集中的列数 36 | int num_fields = mysql_num_fields(result); 37 | 38 | //返回所有字段结构的数组 39 | MYSQL_FIELD *fields = mysql_fetch_fields(result); 40 | 41 | //从结果集中获取下一行,将对应的用户名和密码,存入map中 42 | while (MYSQL_ROW row = mysql_fetch_row(result)) 43 | { 44 | string temp1(row[0]); 45 | string temp2(row[1]); 46 | users[temp1] = temp2; 47 | } 48 | } 49 | 50 | //对文件描述符设置非阻塞 51 | int setnonblocking(int fd) 52 | { 53 | int old_option = fcntl(fd, F_GETFL); 54 | int new_option = old_option | O_NONBLOCK; 55 | fcntl(fd, F_SETFL, new_option); 56 | return old_option; 57 | } 58 | 59 | //将内核事件表注册读事件,ET模式,选择开启EPOLLONESHOT 60 | void addfd(int epollfd, int fd, bool one_shot, int TRIGMode) 61 | { 62 | epoll_event event; 63 | event.data.fd = fd; 64 | 65 | if (1 == TRIGMode) 66 | event.events = EPOLLIN | EPOLLET | EPOLLRDHUP; 67 | else 68 | event.events = EPOLLIN | EPOLLRDHUP; 69 | 70 | if (one_shot) 71 | event.events |= EPOLLONESHOT; 72 | epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event); 73 | setnonblocking(fd); 74 | } 75 | 76 | //从内核时间表删除描述符 77 | void removefd(int epollfd, int fd) 78 | { 79 | epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, 0); 80 | close(fd); 81 | } 82 | 83 | //将事件重置为EPOLLONESHOT 84 | void modfd(int epollfd, int fd, int ev, int TRIGMode) 85 | { 86 | epoll_event event; 87 | event.data.fd = fd; 88 | 89 | if (1 == TRIGMode) 90 | event.events = ev | EPOLLET | EPOLLONESHOT | EPOLLRDHUP; 91 | else 92 | event.events = ev | EPOLLONESHOT | EPOLLRDHUP; 93 | 94 | epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &event); 95 | } 96 | 97 | int http_conn::m_user_count = 0; 98 | int http_conn::m_epollfd = -1; 99 | 100 | //关闭连接,关闭一个连接,客户总量减一 101 | void http_conn::close_conn(bool real_close) 102 | { 103 | if (real_close && (m_sockfd != -1)) 104 | { 105 | printf("close %d\n", m_sockfd); 106 | removefd(m_epollfd, m_sockfd); 107 | m_sockfd = -1; 108 | m_user_count--; 109 | } 110 | } 111 | 112 | //初始化连接,外部调用初始化套接字地址 113 | void http_conn::init(int sockfd, const sockaddr_in &addr, char *root, int TRIGMode, 114 | int close_log, string user, string passwd, string sqlname) 115 | { 116 | m_sockfd = sockfd; 117 | m_address = addr; 118 | 119 | addfd(m_epollfd, sockfd, true, m_TRIGMode); 120 | m_user_count++; 121 | 122 | //当浏览器出现连接重置时,可能是网站根目录出错或http响应格式出错或者访问的文件中内容完全为空 123 | doc_root = root; 124 | m_TRIGMode = TRIGMode; 125 | m_close_log = close_log; 126 | 127 | strcpy(sql_user, user.c_str()); 128 | strcpy(sql_passwd, passwd.c_str()); 129 | strcpy(sql_name, sqlname.c_str()); 130 | 131 | init(); 132 | } 133 | 134 | //初始化新接受的连接 135 | //check_state默认为分析请求行状态 136 | void http_conn::init() 137 | { 138 | mysql = NULL; 139 | bytes_to_send = 0; 140 | bytes_have_send = 0; 141 | m_check_state = CHECK_STATE_REQUESTLINE; 142 | m_linger = false; 143 | m_method = GET; 144 | m_url = 0; 145 | m_version = 0; 146 | m_content_length = 0; 147 | m_host = 0; 148 | m_start_line = 0; 149 | m_checked_idx = 0; 150 | m_read_idx = 0; 151 | m_write_idx = 0; 152 | cgi = 0; 153 | m_state = 0; 154 | timer_flag = 0; 155 | improv = 0; 156 | 157 | memset(m_read_buf, '\0', READ_BUFFER_SIZE); 158 | memset(m_write_buf, '\0', WRITE_BUFFER_SIZE); 159 | memset(m_real_file, '\0', FILENAME_LEN); 160 | } 161 | 162 | //从状态机,用于分析出一行内容 163 | //返回值为行的读取状态,有LINE_OK,LINE_BAD,LINE_OPEN 164 | http_conn::LINE_STATUS http_conn::parse_line() 165 | { 166 | char temp; 167 | for (; m_checked_idx < m_read_idx; ++m_checked_idx) 168 | { 169 | temp = m_read_buf[m_checked_idx]; 170 | if (temp == '\r') 171 | { 172 | if ((m_checked_idx + 1) == m_read_idx) 173 | return LINE_OPEN; 174 | else if (m_read_buf[m_checked_idx + 1] == '\n') 175 | { 176 | m_read_buf[m_checked_idx++] = '\0'; 177 | m_read_buf[m_checked_idx++] = '\0'; 178 | return LINE_OK; 179 | } 180 | return LINE_BAD; 181 | } 182 | else if (temp == '\n') 183 | { 184 | if (m_checked_idx > 1 && m_read_buf[m_checked_idx - 1] == '\r') 185 | { 186 | m_read_buf[m_checked_idx - 1] = '\0'; 187 | m_read_buf[m_checked_idx++] = '\0'; 188 | return LINE_OK; 189 | } 190 | return LINE_BAD; 191 | } 192 | } 193 | return LINE_OPEN; 194 | } 195 | 196 | //循环读取客户数据,直到无数据可读或对方关闭连接 197 | //非阻塞ET工作模式下,需要一次性将数据读完 198 | bool http_conn::read_once() 199 | { 200 | if (m_read_idx >= READ_BUFFER_SIZE) 201 | { 202 | return false; 203 | } 204 | int bytes_read = 0; 205 | 206 | //LT读取数据 207 | if (0 == m_TRIGMode) 208 | { 209 | bytes_read = recv(m_sockfd, m_read_buf + m_read_idx, READ_BUFFER_SIZE - m_read_idx, 0); 210 | m_read_idx += bytes_read; 211 | 212 | if (bytes_read <= 0) 213 | { 214 | return false; 215 | } 216 | 217 | return true; 218 | } 219 | //ET读数据 220 | else 221 | { 222 | while (true) 223 | { 224 | bytes_read = recv(m_sockfd, m_read_buf + m_read_idx, READ_BUFFER_SIZE - m_read_idx, 0); 225 | if (bytes_read == -1) 226 | { 227 | if (errno == EAGAIN || errno == EWOULDBLOCK) 228 | break; 229 | return false; 230 | } 231 | else if (bytes_read == 0) 232 | { 233 | return false; 234 | } 235 | m_read_idx += bytes_read; 236 | } 237 | return true; 238 | } 239 | } 240 | 241 | //解析http请求行,获得请求方法,目标url及http版本号 242 | http_conn::HTTP_CODE http_conn::parse_request_line(char *text) 243 | { 244 | m_url = strpbrk(text, " \t"); 245 | if (!m_url) 246 | { 247 | return BAD_REQUEST; 248 | } 249 | *m_url++ = '\0'; 250 | char *method = text; 251 | if (strcasecmp(method, "GET") == 0) 252 | m_method = GET; 253 | else if (strcasecmp(method, "POST") == 0) 254 | { 255 | m_method = POST; 256 | cgi = 1; 257 | } 258 | else 259 | return BAD_REQUEST; 260 | m_url += strspn(m_url, " \t"); 261 | m_version = strpbrk(m_url, " \t"); 262 | if (!m_version) 263 | return BAD_REQUEST; 264 | *m_version++ = '\0'; 265 | m_version += strspn(m_version, " \t"); 266 | if (strcasecmp(m_version, "HTTP/1.1") != 0) 267 | return BAD_REQUEST; 268 | if (strncasecmp(m_url, "http://", 7) == 0) 269 | { 270 | m_url += 7; 271 | m_url = strchr(m_url, '/'); 272 | } 273 | 274 | if (strncasecmp(m_url, "https://", 8) == 0) 275 | { 276 | m_url += 8; 277 | m_url = strchr(m_url, '/'); 278 | } 279 | 280 | if (!m_url || m_url[0] != '/') 281 | return BAD_REQUEST; 282 | //当url为/时,显示判断界面 283 | if (strlen(m_url) == 1) 284 | strcat(m_url, "judge.html"); 285 | m_check_state = CHECK_STATE_HEADER; 286 | return NO_REQUEST; 287 | } 288 | 289 | //解析http请求的一个头部信息 290 | http_conn::HTTP_CODE http_conn::parse_headers(char *text) 291 | { 292 | if (text[0] == '\0') 293 | { 294 | if (m_content_length != 0) 295 | { 296 | m_check_state = CHECK_STATE_CONTENT; 297 | return NO_REQUEST; 298 | } 299 | return GET_REQUEST; 300 | } 301 | else if (strncasecmp(text, "Connection:", 11) == 0) 302 | { 303 | text += 11; 304 | text += strspn(text, " \t"); 305 | if (strcasecmp(text, "keep-alive") == 0) 306 | { 307 | m_linger = true; 308 | } 309 | } 310 | else if (strncasecmp(text, "Content-length:", 15) == 0) 311 | { 312 | text += 15; 313 | text += strspn(text, " \t"); 314 | m_content_length = atol(text); 315 | } 316 | else if (strncasecmp(text, "Host:", 5) == 0) 317 | { 318 | text += 5; 319 | text += strspn(text, " \t"); 320 | m_host = text; 321 | } 322 | else 323 | { 324 | LOG_INFO("oop!unknow header: %s", text); 325 | } 326 | return NO_REQUEST; 327 | } 328 | 329 | //判断http请求是否被完整读入 330 | http_conn::HTTP_CODE http_conn::parse_content(char *text) 331 | { 332 | if (m_read_idx >= (m_content_length + m_checked_idx)) 333 | { 334 | text[m_content_length] = '\0'; 335 | //POST请求中最后为输入的用户名和密码 336 | m_string = text; 337 | return GET_REQUEST; 338 | } 339 | return NO_REQUEST; 340 | } 341 | 342 | http_conn::HTTP_CODE http_conn::process_read() 343 | { 344 | LINE_STATUS line_status = LINE_OK; 345 | HTTP_CODE ret = NO_REQUEST; 346 | char *text = 0; 347 | 348 | while ((m_check_state == CHECK_STATE_CONTENT && line_status == LINE_OK) || ((line_status = parse_line()) == LINE_OK)) 349 | { 350 | text = get_line(); 351 | m_start_line = m_checked_idx; 352 | LOG_INFO("%s", text); 353 | switch (m_check_state) 354 | { 355 | case CHECK_STATE_REQUESTLINE: 356 | { 357 | ret = parse_request_line(text); 358 | if (ret == BAD_REQUEST) 359 | return BAD_REQUEST; 360 | break; 361 | } 362 | case CHECK_STATE_HEADER: 363 | { 364 | ret = parse_headers(text); 365 | if (ret == BAD_REQUEST) 366 | return BAD_REQUEST; 367 | else if (ret == GET_REQUEST) 368 | { 369 | return do_request(); 370 | } 371 | break; 372 | } 373 | case CHECK_STATE_CONTENT: 374 | { 375 | ret = parse_content(text); 376 | if (ret == GET_REQUEST) 377 | return do_request(); 378 | line_status = LINE_OPEN; 379 | break; 380 | } 381 | default: 382 | return INTERNAL_ERROR; 383 | } 384 | } 385 | return NO_REQUEST; 386 | } 387 | 388 | http_conn::HTTP_CODE http_conn::do_request() 389 | { 390 | strcpy(m_real_file, doc_root); 391 | int len = strlen(doc_root); 392 | //printf("m_url:%s\n", m_url); 393 | const char *p = strrchr(m_url, '/'); 394 | 395 | //处理cgi 396 | if (cgi == 1 && (*(p + 1) == '2' || *(p + 1) == '3')) 397 | { 398 | 399 | //根据标志判断是登录检测还是注册检测 400 | char flag = m_url[1]; 401 | 402 | char *m_url_real = (char *)malloc(sizeof(char) * 200); 403 | strcpy(m_url_real, "/"); 404 | strcat(m_url_real, m_url + 2); 405 | strncpy(m_real_file + len, m_url_real, FILENAME_LEN - len - 1); 406 | free(m_url_real); 407 | 408 | //将用户名和密码提取出来 409 | //user=123&passwd=123 410 | char name[100], password[100]; 411 | int i; 412 | for (i = 5; m_string[i] != '&'; ++i) 413 | name[i - 5] = m_string[i]; 414 | name[i - 5] = '\0'; 415 | 416 | int j = 0; 417 | for (i = i + 10; m_string[i] != '\0'; ++i, ++j) 418 | password[j] = m_string[i]; 419 | password[j] = '\0'; 420 | 421 | if (*(p + 1) == '3') 422 | { 423 | //如果是注册,先检测数据库中是否有重名的 424 | //没有重名的,进行增加数据 425 | char *sql_insert = (char *)malloc(sizeof(char) * 200); 426 | strcpy(sql_insert, "INSERT INTO user(username, passwd) VALUES("); 427 | strcat(sql_insert, "'"); 428 | strcat(sql_insert, name); 429 | strcat(sql_insert, "', '"); 430 | strcat(sql_insert, password); 431 | strcat(sql_insert, "')"); 432 | 433 | if (users.find(name) == users.end()) 434 | { 435 | m_lock.lock(); 436 | int res = mysql_query(mysql, sql_insert); 437 | users.insert(pair(name, password)); 438 | m_lock.unlock(); 439 | 440 | if (!res) 441 | strcpy(m_url, "/log.html"); 442 | else 443 | strcpy(m_url, "/registerError.html"); 444 | } 445 | else 446 | strcpy(m_url, "/registerError.html"); 447 | } 448 | //如果是登录,直接判断 449 | //若浏览器端输入的用户名和密码在表中可以查找到,返回1,否则返回0 450 | else if (*(p + 1) == '2') 451 | { 452 | if (users.find(name) != users.end() && users[name] == password) 453 | strcpy(m_url, "/welcome.html"); 454 | else 455 | strcpy(m_url, "/logError.html"); 456 | } 457 | } 458 | 459 | if (*(p + 1) == '0') 460 | { 461 | char *m_url_real = (char *)malloc(sizeof(char) * 200); 462 | strcpy(m_url_real, "/register.html"); 463 | strncpy(m_real_file + len, m_url_real, strlen(m_url_real)); 464 | 465 | free(m_url_real); 466 | } 467 | else if (*(p + 1) == '1') 468 | { 469 | char *m_url_real = (char *)malloc(sizeof(char) * 200); 470 | strcpy(m_url_real, "/log.html"); 471 | strncpy(m_real_file + len, m_url_real, strlen(m_url_real)); 472 | 473 | free(m_url_real); 474 | } 475 | else if (*(p + 1) == '5') 476 | { 477 | char *m_url_real = (char *)malloc(sizeof(char) * 200); 478 | strcpy(m_url_real, "/picture.html"); 479 | strncpy(m_real_file + len, m_url_real, strlen(m_url_real)); 480 | 481 | free(m_url_real); 482 | } 483 | else if (*(p + 1) == '6') 484 | { 485 | char *m_url_real = (char *)malloc(sizeof(char) * 200); 486 | strcpy(m_url_real, "/video.html"); 487 | strncpy(m_real_file + len, m_url_real, strlen(m_url_real)); 488 | 489 | free(m_url_real); 490 | } 491 | else if (*(p + 1) == '7') 492 | { 493 | char *m_url_real = (char *)malloc(sizeof(char) * 200); 494 | strcpy(m_url_real, "/fans.html"); 495 | strncpy(m_real_file + len, m_url_real, strlen(m_url_real)); 496 | 497 | free(m_url_real); 498 | } 499 | else 500 | strncpy(m_real_file + len, m_url, FILENAME_LEN - len - 1); 501 | 502 | if (stat(m_real_file, &m_file_stat) < 0) 503 | return NO_RESOURCE; 504 | 505 | if (!(m_file_stat.st_mode & S_IROTH)) 506 | return FORBIDDEN_REQUEST; 507 | 508 | if (S_ISDIR(m_file_stat.st_mode)) 509 | return BAD_REQUEST; 510 | 511 | int fd = open(m_real_file, O_RDONLY); 512 | m_file_address = (char *)mmap(0, m_file_stat.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 513 | close(fd); 514 | return FILE_REQUEST; 515 | } 516 | void http_conn::unmap() 517 | { 518 | if (m_file_address) 519 | { 520 | munmap(m_file_address, m_file_stat.st_size); 521 | m_file_address = 0; 522 | } 523 | } 524 | bool http_conn::write() 525 | { 526 | int temp = 0; 527 | 528 | if (bytes_to_send == 0) 529 | { 530 | modfd(m_epollfd, m_sockfd, EPOLLIN, m_TRIGMode); 531 | init(); 532 | return true; 533 | } 534 | 535 | while (1) 536 | { 537 | temp = writev(m_sockfd, m_iv, m_iv_count); 538 | 539 | if (temp < 0) 540 | { 541 | if (errno == EAGAIN) 542 | { 543 | modfd(m_epollfd, m_sockfd, EPOLLOUT, m_TRIGMode); 544 | return true; 545 | } 546 | unmap(); 547 | return false; 548 | } 549 | 550 | bytes_have_send += temp; 551 | bytes_to_send -= temp; 552 | if (bytes_have_send >= m_iv[0].iov_len) 553 | { 554 | m_iv[0].iov_len = 0; 555 | m_iv[1].iov_base = m_file_address + (bytes_have_send - m_write_idx); 556 | m_iv[1].iov_len = bytes_to_send; 557 | } 558 | else 559 | { 560 | m_iv[0].iov_base = m_write_buf + bytes_have_send; 561 | m_iv[0].iov_len = m_iv[0].iov_len - bytes_have_send; 562 | } 563 | 564 | if (bytes_to_send <= 0) 565 | { 566 | unmap(); 567 | modfd(m_epollfd, m_sockfd, EPOLLIN, m_TRIGMode); 568 | 569 | if (m_linger) 570 | { 571 | init(); 572 | return true; 573 | } 574 | else 575 | { 576 | return false; 577 | } 578 | } 579 | } 580 | } 581 | bool http_conn::add_response(const char *format, ...) 582 | { 583 | if (m_write_idx >= WRITE_BUFFER_SIZE) 584 | return false; 585 | va_list arg_list; 586 | va_start(arg_list, format); 587 | int len = vsnprintf(m_write_buf + m_write_idx, WRITE_BUFFER_SIZE - 1 - m_write_idx, format, arg_list); 588 | if (len >= (WRITE_BUFFER_SIZE - 1 - m_write_idx)) 589 | { 590 | va_end(arg_list); 591 | return false; 592 | } 593 | m_write_idx += len; 594 | va_end(arg_list); 595 | 596 | LOG_INFO("request:%s", m_write_buf); 597 | 598 | return true; 599 | } 600 | bool http_conn::add_status_line(int status, const char *title) 601 | { 602 | return add_response("%s %d %s\r\n", "HTTP/1.1", status, title); 603 | } 604 | bool http_conn::add_headers(int content_len) 605 | { 606 | return add_content_length(content_len) && add_linger() && 607 | add_blank_line(); 608 | } 609 | bool http_conn::add_content_length(int content_len) 610 | { 611 | return add_response("Content-Length:%d\r\n", content_len); 612 | } 613 | bool http_conn::add_content_type() 614 | { 615 | return add_response("Content-Type:%s\r\n", "text/html"); 616 | } 617 | bool http_conn::add_linger() 618 | { 619 | return add_response("Connection:%s\r\n", (m_linger == true) ? "keep-alive" : "close"); 620 | } 621 | bool http_conn::add_blank_line() 622 | { 623 | return add_response("%s", "\r\n"); 624 | } 625 | bool http_conn::add_content(const char *content) 626 | { 627 | return add_response("%s", content); 628 | } 629 | bool http_conn::process_write(HTTP_CODE ret) 630 | { 631 | switch (ret) 632 | { 633 | case INTERNAL_ERROR: 634 | { 635 | add_status_line(500, error_500_title); 636 | add_headers(strlen(error_500_form)); 637 | if (!add_content(error_500_form)) 638 | return false; 639 | break; 640 | } 641 | case BAD_REQUEST: 642 | { 643 | add_status_line(404, error_404_title); 644 | add_headers(strlen(error_404_form)); 645 | if (!add_content(error_404_form)) 646 | return false; 647 | break; 648 | } 649 | case FORBIDDEN_REQUEST: 650 | { 651 | add_status_line(403, error_403_title); 652 | add_headers(strlen(error_403_form)); 653 | if (!add_content(error_403_form)) 654 | return false; 655 | break; 656 | } 657 | case FILE_REQUEST: 658 | { 659 | add_status_line(200, ok_200_title); 660 | if (m_file_stat.st_size != 0) 661 | { 662 | add_headers(m_file_stat.st_size); 663 | m_iv[0].iov_base = m_write_buf; 664 | m_iv[0].iov_len = m_write_idx; 665 | m_iv[1].iov_base = m_file_address; 666 | m_iv[1].iov_len = m_file_stat.st_size; 667 | m_iv_count = 2; 668 | bytes_to_send = m_write_idx + m_file_stat.st_size; 669 | return true; 670 | } 671 | else 672 | { 673 | const char *ok_string = ""; 674 | add_headers(strlen(ok_string)); 675 | if (!add_content(ok_string)) 676 | return false; 677 | } 678 | } 679 | default: 680 | return false; 681 | } 682 | m_iv[0].iov_base = m_write_buf; 683 | m_iv[0].iov_len = m_write_idx; 684 | m_iv_count = 1; 685 | bytes_to_send = m_write_idx; 686 | return true; 687 | } 688 | void http_conn::process() 689 | { 690 | HTTP_CODE read_ret = process_read(); 691 | if (read_ret == NO_REQUEST) 692 | { 693 | modfd(m_epollfd, m_sockfd, EPOLLIN, m_TRIGMode); 694 | return; 695 | } 696 | bool write_ret = process_write(read_ret); 697 | if (!write_ret) 698 | { 699 | close_conn(); 700 | } 701 | modfd(m_epollfd, m_sockfd, EPOLLOUT, m_TRIGMode); 702 | } 703 | -------------------------------------------------------------------------------- /http/http_conn.h: -------------------------------------------------------------------------------- 1 | #ifndef HTTPCONNECTION_H 2 | #define HTTPCONNECTION_H 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | #include "../lock/locker.h" 25 | #include "../CGImysql/sql_connection_pool.h" 26 | #include "../timer/lst_timer.h" 27 | #include "../log/log.h" 28 | 29 | class http_conn 30 | { 31 | public: 32 | static const int FILENAME_LEN = 200; 33 | static const int READ_BUFFER_SIZE = 2048; 34 | static const int WRITE_BUFFER_SIZE = 1024; 35 | enum METHOD 36 | { 37 | GET = 0, 38 | POST, 39 | HEAD, 40 | PUT, 41 | DELETE, 42 | TRACE, 43 | OPTIONS, 44 | CONNECT, 45 | PATH 46 | }; 47 | enum CHECK_STATE 48 | { 49 | CHECK_STATE_REQUESTLINE = 0, 50 | CHECK_STATE_HEADER, 51 | CHECK_STATE_CONTENT 52 | }; 53 | enum HTTP_CODE 54 | { 55 | NO_REQUEST, 56 | GET_REQUEST, 57 | BAD_REQUEST, 58 | NO_RESOURCE, 59 | FORBIDDEN_REQUEST, 60 | FILE_REQUEST, 61 | INTERNAL_ERROR, 62 | CLOSED_CONNECTION 63 | }; 64 | enum LINE_STATUS 65 | { 66 | LINE_OK = 0, 67 | LINE_BAD, 68 | LINE_OPEN 69 | }; 70 | 71 | public: 72 | http_conn() {} 73 | ~http_conn() {} 74 | 75 | public: 76 | void init(int sockfd, const sockaddr_in &addr, char *, int, int, string user, string passwd, string sqlname); 77 | void close_conn(bool real_close = true); 78 | void process(); 79 | bool read_once(); 80 | bool write(); 81 | sockaddr_in *get_address() 82 | { 83 | return &m_address; 84 | } 85 | void initmysql_result(connection_pool *connPool); 86 | int timer_flag; 87 | int improv; 88 | 89 | 90 | private: 91 | void init(); 92 | HTTP_CODE process_read(); 93 | bool process_write(HTTP_CODE ret); 94 | HTTP_CODE parse_request_line(char *text); 95 | HTTP_CODE parse_headers(char *text); 96 | HTTP_CODE parse_content(char *text); 97 | HTTP_CODE do_request(); 98 | char *get_line() { return m_read_buf + m_start_line; }; 99 | LINE_STATUS parse_line(); 100 | void unmap(); 101 | bool add_response(const char *format, ...); 102 | bool add_content(const char *content); 103 | bool add_status_line(int status, const char *title); 104 | bool add_headers(int content_length); 105 | bool add_content_type(); 106 | bool add_content_length(int content_length); 107 | bool add_linger(); 108 | bool add_blank_line(); 109 | 110 | public: 111 | static int m_epollfd; 112 | static int m_user_count; 113 | MYSQL *mysql; 114 | int m_state; //读为0, 写为1 115 | 116 | private: 117 | int m_sockfd; 118 | sockaddr_in m_address; 119 | char m_read_buf[READ_BUFFER_SIZE]; 120 | int m_read_idx; 121 | int m_checked_idx; 122 | int m_start_line; 123 | char m_write_buf[WRITE_BUFFER_SIZE]; 124 | int m_write_idx; 125 | CHECK_STATE m_check_state; 126 | METHOD m_method; 127 | char m_real_file[FILENAME_LEN]; 128 | char *m_url; 129 | char *m_version; 130 | char *m_host; 131 | int m_content_length; 132 | bool m_linger; 133 | char *m_file_address; 134 | struct stat m_file_stat; 135 | struct iovec m_iv[2]; 136 | int m_iv_count; 137 | int cgi; //是否启用的POST 138 | char *m_string; //存储请求头数据 139 | int bytes_to_send; 140 | int bytes_have_send; 141 | char *doc_root; 142 | 143 | map m_users; 144 | int m_TRIGMode; 145 | int m_close_log; 146 | 147 | char sql_user[100]; 148 | char sql_passwd[100]; 149 | char sql_name[100]; 150 | }; 151 | 152 | #endif 153 | -------------------------------------------------------------------------------- /lock/README.md: -------------------------------------------------------------------------------- 1 | 2 | 线程同步机制包装类 3 | =============== 4 | 多线程同步,确保任一时刻只能有一个线程能进入关键代码段. 5 | > * 信号量 6 | > * 互斥锁 7 | > * 条件变量 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /lock/locker.h: -------------------------------------------------------------------------------- 1 | #ifndef LOCKER_H 2 | #define LOCKER_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | class sem 9 | { 10 | public: 11 | sem() 12 | { 13 | if (sem_init(&m_sem, 0, 0) != 0) 14 | { 15 | throw std::exception(); 16 | } 17 | } 18 | sem(int num) 19 | { 20 | if (sem_init(&m_sem, 0, num) != 0) 21 | { 22 | throw std::exception(); 23 | } 24 | } 25 | ~sem() 26 | { 27 | sem_destroy(&m_sem); 28 | } 29 | bool wait() 30 | { 31 | return sem_wait(&m_sem) == 0; 32 | } 33 | bool post() 34 | { 35 | return sem_post(&m_sem) == 0; 36 | } 37 | 38 | private: 39 | sem_t m_sem; 40 | }; 41 | class locker 42 | { 43 | public: 44 | locker() 45 | { 46 | if (pthread_mutex_init(&m_mutex, NULL) != 0) 47 | { 48 | throw std::exception(); 49 | } 50 | } 51 | ~locker() 52 | { 53 | pthread_mutex_destroy(&m_mutex); 54 | } 55 | bool lock() 56 | { 57 | return pthread_mutex_lock(&m_mutex) == 0; 58 | } 59 | bool unlock() 60 | { 61 | return pthread_mutex_unlock(&m_mutex) == 0; 62 | } 63 | pthread_mutex_t *get() 64 | { 65 | return &m_mutex; 66 | } 67 | 68 | private: 69 | pthread_mutex_t m_mutex; 70 | }; 71 | class cond 72 | { 73 | public: 74 | cond() 75 | { 76 | if (pthread_cond_init(&m_cond, NULL) != 0) 77 | { 78 | //pthread_mutex_destroy(&m_mutex); 79 | throw std::exception(); 80 | } 81 | } 82 | ~cond() 83 | { 84 | pthread_cond_destroy(&m_cond); 85 | } 86 | bool wait(pthread_mutex_t *m_mutex) 87 | { 88 | int ret = 0; 89 | //pthread_mutex_lock(&m_mutex); 90 | ret = pthread_cond_wait(&m_cond, m_mutex); 91 | //pthread_mutex_unlock(&m_mutex); 92 | return ret == 0; 93 | } 94 | bool timewait(pthread_mutex_t *m_mutex, struct timespec t) 95 | { 96 | int ret = 0; 97 | //pthread_mutex_lock(&m_mutex); 98 | ret = pthread_cond_timedwait(&m_cond, m_mutex, &t); 99 | //pthread_mutex_unlock(&m_mutex); 100 | return ret == 0; 101 | } 102 | bool signal() 103 | { 104 | return pthread_cond_signal(&m_cond) == 0; 105 | } 106 | bool broadcast() 107 | { 108 | return pthread_cond_broadcast(&m_cond) == 0; 109 | } 110 | 111 | private: 112 | //static pthread_mutex_t m_mutex; 113 | pthread_cond_t m_cond; 114 | }; 115 | #endif 116 | -------------------------------------------------------------------------------- /log/README.md: -------------------------------------------------------------------------------- 1 | 2 | 同步/异步日志系统 3 | =============== 4 | 同步/异步日志系统主要涉及了两个模块,一个是日志模块,一个是阻塞队列模块,其中加入阻塞队列模块主要是解决异步写入日志做准备. 5 | > * 自定义阻塞队列 6 | > * 单例模式创建日志 7 | > * 同步日志 8 | > * 异步日志 9 | > * 实现按天、超行分类 10 | -------------------------------------------------------------------------------- /log/block_queue.h: -------------------------------------------------------------------------------- 1 | /************************************************************* 2 | *循环数组实现的阻塞队列,m_back = (m_back + 1) % m_max_size; 3 | *线程安全,每个操作前都要先加互斥锁,操作完后,再解锁 4 | **************************************************************/ 5 | 6 | #ifndef BLOCK_QUEUE_H 7 | #define BLOCK_QUEUE_H 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "../lock/locker.h" 14 | using namespace std; 15 | 16 | template 17 | class block_queue 18 | { 19 | public: 20 | block_queue(int max_size = 1000) 21 | { 22 | if (max_size <= 0) 23 | { 24 | exit(-1); 25 | } 26 | 27 | m_max_size = max_size; 28 | m_array = new T[max_size]; 29 | m_size = 0; 30 | m_front = -1; 31 | m_back = -1; 32 | } 33 | 34 | void clear() 35 | { 36 | m_mutex.lock(); 37 | m_size = 0; 38 | m_front = -1; 39 | m_back = -1; 40 | m_mutex.unlock(); 41 | } 42 | 43 | ~block_queue() 44 | { 45 | m_mutex.lock(); 46 | if (m_array != NULL) 47 | delete [] m_array; 48 | 49 | m_mutex.unlock(); 50 | } 51 | //判断队列是否满了 52 | bool full() 53 | { 54 | m_mutex.lock(); 55 | if (m_size >= m_max_size) 56 | { 57 | 58 | m_mutex.unlock(); 59 | return true; 60 | } 61 | m_mutex.unlock(); 62 | return false; 63 | } 64 | //判断队列是否为空 65 | bool empty() 66 | { 67 | m_mutex.lock(); 68 | if (0 == m_size) 69 | { 70 | m_mutex.unlock(); 71 | return true; 72 | } 73 | m_mutex.unlock(); 74 | return false; 75 | } 76 | //返回队首元素 77 | bool front(T &value) 78 | { 79 | m_mutex.lock(); 80 | if (0 == m_size) 81 | { 82 | m_mutex.unlock(); 83 | return false; 84 | } 85 | value = m_array[m_front]; 86 | m_mutex.unlock(); 87 | return true; 88 | } 89 | //返回队尾元素 90 | bool back(T &value) 91 | { 92 | m_mutex.lock(); 93 | if (0 == m_size) 94 | { 95 | m_mutex.unlock(); 96 | return false; 97 | } 98 | value = m_array[m_back]; 99 | m_mutex.unlock(); 100 | return true; 101 | } 102 | 103 | int size() 104 | { 105 | int tmp = 0; 106 | 107 | m_mutex.lock(); 108 | tmp = m_size; 109 | 110 | m_mutex.unlock(); 111 | return tmp; 112 | } 113 | 114 | int max_size() 115 | { 116 | int tmp = 0; 117 | 118 | m_mutex.lock(); 119 | tmp = m_max_size; 120 | 121 | m_mutex.unlock(); 122 | return tmp; 123 | } 124 | //往队列添加元素,需要将所有使用队列的线程先唤醒 125 | //当有元素push进队列,相当于生产者生产了一个元素 126 | //若当前没有线程等待条件变量,则唤醒无意义 127 | bool push(const T &item) 128 | { 129 | 130 | m_mutex.lock(); 131 | if (m_size >= m_max_size) 132 | { 133 | 134 | m_cond.broadcast(); 135 | m_mutex.unlock(); 136 | return false; 137 | } 138 | 139 | m_back = (m_back + 1) % m_max_size; 140 | m_array[m_back] = item; 141 | 142 | m_size++; 143 | 144 | m_cond.broadcast(); 145 | m_mutex.unlock(); 146 | return true; 147 | } 148 | //pop时,如果当前队列没有元素,将会等待条件变量 149 | bool pop(T &item) 150 | { 151 | 152 | m_mutex.lock(); 153 | while (m_size <= 0) 154 | { 155 | 156 | if (!m_cond.wait(m_mutex.get())) 157 | { 158 | m_mutex.unlock(); 159 | return false; 160 | } 161 | } 162 | 163 | m_front = (m_front + 1) % m_max_size; 164 | item = m_array[m_front]; 165 | m_size--; 166 | m_mutex.unlock(); 167 | return true; 168 | } 169 | 170 | //增加了超时处理 171 | bool pop(T &item, int ms_timeout) 172 | { 173 | struct timespec t = {0, 0}; 174 | struct timeval now = {0, 0}; 175 | gettimeofday(&now, NULL); 176 | m_mutex.lock(); 177 | if (m_size <= 0) 178 | { 179 | t.tv_sec = now.tv_sec + ms_timeout / 1000; 180 | t.tv_nsec = (ms_timeout % 1000) * 1000; 181 | if (!m_cond.timewait(m_mutex.get(), t)) 182 | { 183 | m_mutex.unlock(); 184 | return false; 185 | } 186 | } 187 | 188 | if (m_size <= 0) 189 | { 190 | m_mutex.unlock(); 191 | return false; 192 | } 193 | 194 | m_front = (m_front + 1) % m_max_size; 195 | item = m_array[m_front]; 196 | m_size--; 197 | m_mutex.unlock(); 198 | return true; 199 | } 200 | 201 | private: 202 | locker m_mutex; 203 | cond m_cond; 204 | 205 | T *m_array; 206 | int m_size; 207 | int m_max_size; 208 | int m_front; 209 | int m_back; 210 | }; 211 | 212 | #endif 213 | -------------------------------------------------------------------------------- /log/log.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "log.h" 6 | #include 7 | using namespace std; 8 | 9 | Log::Log() 10 | { 11 | m_count = 0; 12 | m_is_async = false; 13 | } 14 | 15 | Log::~Log() 16 | { 17 | if (m_fp != NULL) 18 | { 19 | fclose(m_fp); 20 | } 21 | } 22 | //异步需要设置阻塞队列的长度,同步不需要设置 23 | bool Log::init(const char *file_name, int close_log, int log_buf_size, int split_lines, int max_queue_size) 24 | { 25 | //如果设置了max_queue_size,则设置为异步 26 | if (max_queue_size >= 1) 27 | { 28 | m_is_async = true; 29 | m_log_queue = new block_queue(max_queue_size); 30 | pthread_t tid; 31 | //flush_log_thread为回调函数,这里表示创建线程异步写日志 32 | pthread_create(&tid, NULL, flush_log_thread, NULL); 33 | } 34 | 35 | m_close_log = close_log; 36 | m_log_buf_size = log_buf_size; 37 | m_buf = new char[m_log_buf_size]; 38 | memset(m_buf, '\0', m_log_buf_size); 39 | m_split_lines = split_lines; 40 | 41 | time_t t = time(NULL); 42 | struct tm *sys_tm = localtime(&t); 43 | struct tm my_tm = *sys_tm; 44 | 45 | 46 | const char *p = strrchr(file_name, '/'); 47 | char log_full_name[256] = {0}; 48 | 49 | if (p == NULL) 50 | { 51 | snprintf(log_full_name, 255, "%d_%02d_%02d_%s", my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday, file_name); 52 | } 53 | else 54 | { 55 | strcpy(log_name, p + 1); 56 | strncpy(dir_name, file_name, p - file_name + 1); 57 | snprintf(log_full_name, 255, "%s%d_%02d_%02d_%s", dir_name, my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday, log_name); 58 | } 59 | 60 | m_today = my_tm.tm_mday; 61 | 62 | m_fp = fopen(log_full_name, "a"); 63 | if (m_fp == NULL) 64 | { 65 | return false; 66 | } 67 | 68 | return true; 69 | } 70 | 71 | void Log::write_log(int level, const char *format, ...) 72 | { 73 | struct timeval now = {0, 0}; 74 | gettimeofday(&now, NULL); 75 | time_t t = now.tv_sec; 76 | struct tm *sys_tm = localtime(&t); 77 | struct tm my_tm = *sys_tm; 78 | char s[16] = {0}; 79 | switch (level) 80 | { 81 | case 0: 82 | strcpy(s, "[debug]:"); 83 | break; 84 | case 1: 85 | strcpy(s, "[info]:"); 86 | break; 87 | case 2: 88 | strcpy(s, "[warn]:"); 89 | break; 90 | case 3: 91 | strcpy(s, "[erro]:"); 92 | break; 93 | default: 94 | strcpy(s, "[info]:"); 95 | break; 96 | } 97 | //写入一个log,对m_count++, m_split_lines最大行数 98 | m_mutex.lock(); 99 | m_count++; 100 | 101 | if (m_today != my_tm.tm_mday || m_count % m_split_lines == 0) //everyday log 102 | { 103 | 104 | char new_log[256] = {0}; 105 | fflush(m_fp); 106 | fclose(m_fp); 107 | char tail[16] = {0}; 108 | 109 | snprintf(tail, 16, "%d_%02d_%02d_", my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday); 110 | 111 | if (m_today != my_tm.tm_mday) 112 | { 113 | snprintf(new_log, 255, "%s%s%s", dir_name, tail, log_name); 114 | m_today = my_tm.tm_mday; 115 | m_count = 0; 116 | } 117 | else 118 | { 119 | snprintf(new_log, 255, "%s%s%s.%lld", dir_name, tail, log_name, m_count / m_split_lines); 120 | } 121 | m_fp = fopen(new_log, "a"); 122 | } 123 | 124 | m_mutex.unlock(); 125 | 126 | va_list valst; 127 | va_start(valst, format); 128 | 129 | string log_str; 130 | m_mutex.lock(); 131 | 132 | //写入的具体时间内容格式 133 | int n = snprintf(m_buf, 48, "%d-%02d-%02d %02d:%02d:%02d.%06ld %s ", 134 | my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday, 135 | my_tm.tm_hour, my_tm.tm_min, my_tm.tm_sec, now.tv_usec, s); 136 | 137 | int m = vsnprintf(m_buf + n, m_log_buf_size - 1, format, valst); 138 | m_buf[n + m] = '\n'; 139 | m_buf[n + m + 1] = '\0'; 140 | log_str = m_buf; 141 | 142 | m_mutex.unlock(); 143 | 144 | if (m_is_async && !m_log_queue->full()) 145 | { 146 | m_log_queue->push(log_str); 147 | } 148 | else 149 | { 150 | m_mutex.lock(); 151 | fputs(log_str.c_str(), m_fp); 152 | m_mutex.unlock(); 153 | } 154 | 155 | va_end(valst); 156 | } 157 | 158 | void Log::flush(void) 159 | { 160 | m_mutex.lock(); 161 | //强制刷新写入流缓冲区 162 | fflush(m_fp); 163 | m_mutex.unlock(); 164 | } 165 | -------------------------------------------------------------------------------- /log/log.h: -------------------------------------------------------------------------------- 1 | #ifndef LOG_H 2 | #define LOG_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "block_queue.h" 10 | 11 | using namespace std; 12 | 13 | class Log 14 | { 15 | public: 16 | //C++11以后,使用局部变量懒汉不用加锁 17 | static Log *get_instance() 18 | { 19 | static Log instance; 20 | return &instance; 21 | } 22 | 23 | static void *flush_log_thread(void *args) 24 | { 25 | Log::get_instance()->async_write_log(); 26 | } 27 | //可选择的参数有日志文件、日志缓冲区大小、最大行数以及最长日志条队列 28 | bool init(const char *file_name, int close_log, int log_buf_size = 8192, int split_lines = 5000000, int max_queue_size = 0); 29 | 30 | void write_log(int level, const char *format, ...); 31 | 32 | void flush(void); 33 | 34 | private: 35 | Log(); 36 | virtual ~Log(); 37 | void *async_write_log() 38 | { 39 | string single_log; 40 | //从阻塞队列中取出一个日志string,写入文件 41 | while (m_log_queue->pop(single_log)) 42 | { 43 | m_mutex.lock(); 44 | fputs(single_log.c_str(), m_fp); 45 | m_mutex.unlock(); 46 | } 47 | } 48 | 49 | private: 50 | char dir_name[128]; //路径名 51 | char log_name[128]; //log文件名 52 | int m_split_lines; //日志最大行数 53 | int m_log_buf_size; //日志缓冲区大小 54 | long long m_count; //日志行数记录 55 | int m_today; //因为按天分类,记录当前时间是那一天 56 | FILE *m_fp; //打开log的文件指针 57 | char *m_buf; 58 | block_queue *m_log_queue; //阻塞队列 59 | bool m_is_async; //是否同步标志位 60 | locker m_mutex; 61 | int m_close_log; //关闭日志 62 | }; 63 | 64 | #define LOG_DEBUG(format, ...) if(0 == m_close_log) {Log::get_instance()->write_log(0, format, ##__VA_ARGS__); Log::get_instance()->flush();} 65 | #define LOG_INFO(format, ...) if(0 == m_close_log) {Log::get_instance()->write_log(1, format, ##__VA_ARGS__); Log::get_instance()->flush();} 66 | #define LOG_WARN(format, ...) if(0 == m_close_log) {Log::get_instance()->write_log(2, format, ##__VA_ARGS__); Log::get_instance()->flush();} 67 | #define LOG_ERROR(format, ...) if(0 == m_close_log) {Log::get_instance()->write_log(3, format, ##__VA_ARGS__); Log::get_instance()->flush();} 68 | 69 | #endif 70 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include "config.h" 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | //需要修改的数据库信息,登录名,密码,库名 6 | string user = "root"; 7 | string passwd = "root"; 8 | string databasename = "qgydb"; 9 | 10 | //命令行解析 11 | Config config; 12 | config.parse_arg(argc, argv); 13 | 14 | WebServer server; 15 | 16 | //初始化 17 | server.init(config.PORT, user, passwd, databasename, config.LOGWrite, 18 | config.OPT_LINGER, config.TRIGMode, config.sql_num, config.thread_num, 19 | config.close_log, config.actor_model); 20 | 21 | 22 | //日志 23 | server.log_write(); 24 | 25 | //数据库 26 | server.sql_pool(); 27 | 28 | //线程池 29 | server.thread_pool(); 30 | 31 | //触发模式 32 | server.trig_mode(); 33 | 34 | //监听 35 | server.eventListen(); 36 | 37 | //运行 38 | server.eventLoop(); 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | CXX ?= g++ 2 | 3 | DEBUG ?= 1 4 | ifeq ($(DEBUG), 1) 5 | CXXFLAGS += -g 6 | else 7 | CXXFLAGS += -O2 8 | 9 | endif 10 | 11 | server: main.cpp ./timer/lst_timer.cpp ./http/http_conn.cpp ./log/log.cpp ./CGImysql/sql_connection_pool.cpp webserver.cpp config.cpp 12 | $(CXX) -o server $^ $(CXXFLAGS) -lpthread -lmysqlclient 13 | 14 | clean: 15 | rm -r server 16 | -------------------------------------------------------------------------------- /root/README.md: -------------------------------------------------------------------------------- 1 | 界面跳转 2 | =============== 3 | 对html中action行为设置标志位,将method设置为POST 4 | > * 0 注册 5 | > * 1 登录 6 | > * 2 登录检测 7 | > * 3 注册检测 8 | > * 5 请求图片 9 | > * 6 请求视频 10 | > * 7 关注我 11 | -------------------------------------------------------------------------------- /root/fans.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | awsl 6 | 7 |
8 |
9 |
嘿嘿,你来啦,更多资料,请关注 “两猿社” 喔.
10 |
11 | 12 |
13 |
14 |
15 | 16 | -------------------------------------------------------------------------------- /root/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/root/favicon.ico -------------------------------------------------------------------------------- /root/frame.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/root/frame.jpg -------------------------------------------------------------------------------- /root/judge.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | WebServer 6 | 7 | 8 |
9 |
10 |
欢迎访问
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /root/log.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Sign in 6 | 7 | 8 |
9 |
10 |
登录
11 |
12 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /root/logError.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Sign in 6 | 7 | 8 |
9 |
10 |
登录
11 |
12 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /root/login.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/root/login.gif -------------------------------------------------------------------------------- /root/loginnew.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/root/loginnew.gif -------------------------------------------------------------------------------- /root/picture.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/root/picture.gif -------------------------------------------------------------------------------- /root/picture.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | awsl 6 | 7 |
8 |
9 |
你居然想看图,不想关注我
10 |
11 | 12 |
13 |
14 |
15 | 16 | -------------------------------------------------------------------------------- /root/register.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/root/register.gif -------------------------------------------------------------------------------- /root/register.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Sign up 6 | 7 | 8 |
9 |
10 |
注册
11 |
12 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /root/registerError.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Sign up 6 | 7 | 8 |
9 |
10 |
注册
11 |
12 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /root/registernew.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/root/registernew.gif -------------------------------------------------------------------------------- /root/test1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/root/test1.jpg -------------------------------------------------------------------------------- /root/video.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/root/video.gif -------------------------------------------------------------------------------- /root/video.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | awsl 6 | 7 |
8 |
9 |
你居然想看视频,不想关注我
10 |
11 | 12 |
13 |
14 |
17 | 18 | -------------------------------------------------------------------------------- /root/welcome.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | WebServer 6 | 7 | 8 |
9 |
10 |
是时候做出选择了
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /root/xxx.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/root/xxx.jpg -------------------------------------------------------------------------------- /root/xxx.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/root/xxx.mp4 -------------------------------------------------------------------------------- /test_presure/README.md: -------------------------------------------------------------------------------- 1 | 服务器压力测试 2 | =============== 3 | Webbench是有名的网站压力测试工具,它是由[Lionbridge](http://www.lionbridge.com)公司开发。 4 | 5 | > * 测试处在相同硬件上,不同服务的性能以及不同硬件上同一个服务的运行状况。 6 | > * 展示服务器的两项内容:每秒钟响应请求数和每秒钟传输数据量。 7 | 8 | 9 | 10 | 11 | 测试规则 12 | ------------ 13 | * 测试示例 14 | 15 | ```C++ 16 | webbench -c 500 -t 30 http://127.0.0.1/phpionfo.php 17 | ``` 18 | * 参数 19 | 20 | > * `-c` 表示客户端数 21 | > * `-t` 表示时间 22 | 23 | 24 | 测试结果 25 | --------- 26 | Webbench对服务器进行压力测试,经压力测试可以实现上万的并发连接. 27 | > * 并发连接总数:10500 28 | > * 访问服务器时间:5s 29 | > * 每秒钟响应请求数:552852 pages/min 30 | > * 每秒钟传输数据量:1031990 bytes/sec 31 | > * 所有访问均成功 32 | 33 |
34 | -------------------------------------------------------------------------------- /test_presure/webbench-1.5/COPYRIGHT: -------------------------------------------------------------------------------- 1 | debian/copyright -------------------------------------------------------------------------------- /test_presure/webbench-1.5/ChangeLog: -------------------------------------------------------------------------------- 1 | debian/changelog -------------------------------------------------------------------------------- /test_presure/webbench-1.5/Makefile: -------------------------------------------------------------------------------- 1 | CFLAGS?= -Wall -ggdb -W -O 2 | CC?= gcc 3 | LIBS?= 4 | LDFLAGS?= 5 | PREFIX?= /usr/local 6 | VERSION=1.5 7 | TMPDIR=/tmp/webbench-$(VERSION) 8 | 9 | all: webbench tags 10 | 11 | tags: *.c 12 | -ctags *.c 13 | 14 | install: webbench 15 | install -s webbench $(DESTDIR)$(PREFIX)/bin 16 | install -m 644 webbench.1 $(DESTDIR)$(PREFIX)/man/man1 17 | install -d $(DESTDIR)$(PREFIX)/share/doc/webbench 18 | install -m 644 debian/copyright $(DESTDIR)$(PREFIX)/share/doc/webbench 19 | install -m 644 debian/changelog $(DESTDIR)$(PREFIX)/share/doc/webbench 20 | 21 | webbench: webbench.o Makefile 22 | $(CC) $(CFLAGS) $(LDFLAGS) -o webbench webbench.o $(LIBS) 23 | 24 | clean: 25 | -rm -f *.o webbench *~ core *.core tags 26 | 27 | tar: clean 28 | -debian/rules clean 29 | rm -rf $(TMPDIR) 30 | install -d $(TMPDIR) 31 | cp -p Makefile webbench.c socket.c webbench.1 $(TMPDIR) 32 | install -d $(TMPDIR)/debian 33 | -cp -p debian/* $(TMPDIR)/debian 34 | ln -sf debian/copyright $(TMPDIR)/COPYRIGHT 35 | ln -sf debian/changelog $(TMPDIR)/ChangeLog 36 | -cd $(TMPDIR) && cd .. && tar cozf webbench-$(VERSION).tar.gz webbench-$(VERSION) 37 | 38 | webbench.o: webbench.c socket.c Makefile 39 | 40 | .PHONY: clean install all tar 41 | -------------------------------------------------------------------------------- /test_presure/webbench-1.5/debian/changelog: -------------------------------------------------------------------------------- 1 | webbench (1.5) unstable; urgency=low 2 | 3 | * allow building with both Gnu and BSD make 4 | 5 | -- Radim Kolar Fri, Jun 25 12:00:20 CEST 2004 6 | 7 | webbench (1.4) unstable; urgency=low 8 | 9 | * check if url is not too long 10 | * report correct program version number 11 | * use yield() when waiting for test start 12 | * corrected error codes 13 | * check availability of test server first 14 | * do not abort test if first request failed 15 | * report when some childrens are dead. 16 | * use alarm, not time() for lower syscal use by bench 17 | * use mode 644 for installed doc 18 | * makefile cleaned for better freebsd ports integration 19 | 20 | -- Radim Kolar Thu, 15 Jan 2004 11:15:52 +0100 21 | 22 | webbench (1.3) unstable; urgency=low 23 | 24 | * Build fixes for freeBSD 25 | * Default benchmark time 60 -> 30 26 | * generate tar with subdirectory 27 | * added to freeBSD ports collection 28 | 29 | -- Radim Kolar Mon, 12 Jan 2004 17:00:24 +0100 30 | 31 | webbench (1.2) unstable; urgency=low 32 | 33 | * Only debian-related bugfixes 34 | * Updated Debian/rules 35 | * Adapted to fit new directory system 36 | * moved from debstd to dh_* 37 | 38 | -- Radim Kolar Fri, 18 Jan 2002 12:33:04 +0100 39 | 40 | webbench (1.1) unstable; urgency=medium 41 | 42 | * Program debianized 43 | * added support for multiple methods (GET, HEAD, OPTIONS, TRACE) 44 | * added support for multiple HTTP versions (0.9 -- 1.1) 45 | * added long options 46 | * added multiple clients 47 | * wait for start of second before test 48 | * test time can be specified 49 | * better error checking when reading reply from server 50 | * FIX: tests was one second longer than expected 51 | 52 | -- Radim Kolar Thu, 16 Sep 1999 18:48:00 +0200 53 | 54 | Local variables: 55 | mode: debian-changelog 56 | End: 57 | -------------------------------------------------------------------------------- /test_presure/webbench-1.5/debian/control: -------------------------------------------------------------------------------- 1 | Source: webbench 2 | Section: web 3 | Priority: extra 4 | Maintainer: Radim Kolar 5 | Build-Depends: debhelper (>> 3.0.0) 6 | Standards-Version: 3.5.2 7 | 8 | Package: webbench 9 | Architecture: any 10 | Depends: ${shlibs:Depends} 11 | Description: Simple forking Web benchmark 12 | webbench is very simple program for benchmarking WWW or Proxy servers. 13 | Uses fork() for simulating multiple clients load. Can use HTTP 0.9 - 1.1 14 | requests, but Keep-Alive connections are not supported. 15 | -------------------------------------------------------------------------------- /test_presure/webbench-1.5/debian/copyright: -------------------------------------------------------------------------------- 1 | Webbench was written by Radim Kolar 1997-2004 (hsn@netmag.cz). 2 | 3 | UNIX sockets code (socket.c) taken from popclient 1.5 4/1/94 4 | public domain code, created by Virginia Tech Computing Center. 5 | 6 | Copyright: GPL (see /usr/share/common-licenses/GPL) 7 | -------------------------------------------------------------------------------- /test_presure/webbench-1.5/debian/dirs: -------------------------------------------------------------------------------- 1 | usr/bin -------------------------------------------------------------------------------- /test_presure/webbench-1.5/debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | # Sample debian/rules that uses debhelper. 3 | # GNU copyright 1997 to 1999 by Joey Hess. 4 | 5 | # Uncomment this to turn on verbose mode. 6 | #export DH_VERBOSE=1 7 | 8 | # This is the debhelper compatability version to use. 9 | export DH_COMPAT=3 10 | 11 | configure: configure-stamp 12 | configure-stamp: 13 | dh_testdir 14 | touch configure-stamp 15 | 16 | build: configure-stamp build-stamp 17 | build-stamp: 18 | dh_testdir 19 | $(MAKE) 20 | touch build-stamp 21 | 22 | clean: 23 | dh_testdir 24 | rm -f build-stamp configure-stamp 25 | 26 | # Add here commands to clean up after the build process. 27 | -$(MAKE) clean 28 | 29 | dh_clean 30 | 31 | install: build 32 | dh_testdir 33 | dh_testroot 34 | dh_clean -k 35 | dh_installdirs 36 | 37 | # Add here commands to install the package into debian/webbench. 38 | $(MAKE) install DESTDIR=$(CURDIR)/debian/webbench 39 | 40 | 41 | # Build architecture-independent files here. 42 | binary-indep: build install 43 | # We have nothing to do by default. 44 | 45 | # Build architecture-dependent files here. 46 | binary-arch: build install 47 | dh_testdir 48 | dh_testroot 49 | dh_installdocs 50 | dh_installman webbench.1 51 | dh_installchangelogs 52 | dh_link 53 | dh_strip 54 | dh_compress 55 | dh_fixperms 56 | # dh_makeshlibs 57 | dh_installdeb 58 | dh_shlibdeps 59 | dh_gencontrol 60 | dh_md5sums 61 | dh_builddeb 62 | 63 | binary: binary-indep binary-arch 64 | .PHONY: build clean binary-indep binary-arch binary install configure 65 | -------------------------------------------------------------------------------- /test_presure/webbench-1.5/socket.c: -------------------------------------------------------------------------------- 1 | /* $Id: socket.c 1.1 1995/01/01 07:11:14 cthuang Exp $ 2 | * 3 | * This module has been modified by Radim Kolar for OS/2 emx 4 | */ 5 | 6 | /*********************************************************************** 7 | module: socket.c 8 | program: popclient 9 | SCCS ID: @(#)socket.c 1.5 4/1/94 10 | programmer: Virginia Tech Computing Center 11 | compiler: DEC RISC C compiler (Ultrix 4.1) 12 | environment: DEC Ultrix 4.3 13 | description: UNIX sockets code. 14 | ***********************************************************************/ 15 | 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | int Socket(const char *host, int clientPort) 30 | { 31 | int sock; 32 | unsigned long inaddr; 33 | struct sockaddr_in ad; 34 | struct hostent *hp; 35 | 36 | memset(&ad, 0, sizeof(ad)); 37 | ad.sin_family = AF_INET; 38 | 39 | inaddr = inet_addr(host); 40 | if (inaddr != INADDR_NONE) 41 | memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr)); 42 | else 43 | { 44 | hp = gethostbyname(host); 45 | if (hp == NULL) 46 | return -1; 47 | memcpy(&ad.sin_addr, hp->h_addr, hp->h_length); 48 | } 49 | ad.sin_port = htons(clientPort); 50 | 51 | sock = socket(AF_INET, SOCK_STREAM, 0); 52 | if (sock < 0) 53 | return sock; 54 | if (connect(sock, (struct sockaddr *)&ad, sizeof(ad)) < 0) 55 | return -1; 56 | return sock; 57 | } 58 | 59 | -------------------------------------------------------------------------------- /test_presure/webbench-1.5/tags: -------------------------------------------------------------------------------- 1 | !_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/ 2 | !_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/ 3 | !_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/ 4 | !_TAG_PROGRAM_NAME Exuberant Ctags // 5 | !_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/ 6 | !_TAG_PROGRAM_VERSION 5.9~svn20110310 // 7 | METHOD_GET webbench.c 35;" d file: 8 | METHOD_HEAD webbench.c 36;" d file: 9 | METHOD_OPTIONS webbench.c 37;" d file: 10 | METHOD_TRACE webbench.c 38;" d file: 11 | PROGRAM_VERSION webbench.c 39;" d file: 12 | REQUEST_SIZE webbench.c 50;" d file: 13 | Socket socket.c /^int Socket(const char *host, int clientPort)$/;" f 14 | alarm_handler webbench.c /^static void alarm_handler(int signal)$/;" f file: 15 | bench webbench.c /^static int bench(void)$/;" f file: 16 | benchcore webbench.c /^void benchcore(const char *host,const int port,const char *req)$/;" f 17 | benchtime webbench.c /^int benchtime=30;$/;" v 18 | build_request webbench.c /^void build_request(const char *url)$/;" f 19 | bytes webbench.c /^int bytes=0;$/;" v 20 | clients webbench.c /^int clients=1;$/;" v 21 | failed webbench.c /^int failed=0;$/;" v 22 | force webbench.c /^int force=0;$/;" v 23 | force_reload webbench.c /^int force_reload=0;$/;" v 24 | host webbench.c /^char host[MAXHOSTNAMELEN];$/;" v 25 | http10 webbench.c /^int http10=1; \/* 0 - http\/0.9, 1 - http\/1.0, 2 - http\/1.1 *\/$/;" v 26 | long_options webbench.c /^static const struct option long_options[]=$/;" v typeref:struct:option file: 27 | main webbench.c /^int main(int argc, char *argv[])$/;" f 28 | method webbench.c /^int method=METHOD_GET;$/;" v 29 | mypipe webbench.c /^int mypipe[2];$/;" v 30 | proxyhost webbench.c /^char *proxyhost=NULL;$/;" v 31 | proxyport webbench.c /^int proxyport=80;$/;" v 32 | request webbench.c /^char request[REQUEST_SIZE];$/;" v 33 | speed webbench.c /^int speed=0;$/;" v 34 | timerexpired webbench.c /^volatile int timerexpired=0;$/;" v 35 | usage webbench.c /^static void usage(void)$/;" f file: 36 | -------------------------------------------------------------------------------- /test_presure/webbench-1.5/webbench: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/test_presure/webbench-1.5/webbench -------------------------------------------------------------------------------- /test_presure/webbench-1.5/webbench.1: -------------------------------------------------------------------------------- 1 | .TH WEBBENCH 1 "14 Jan 2004" 2 | .\" NAME should be all caps, SECTION should be 1-8, maybe w/ subsection 3 | .\" other parms are allowed: see man(7), man(1) 4 | .SH NAME 5 | webbench \- simple forking web benchmark 6 | .SH SYNOPSIS 7 | .B webbench 8 | .I "[options] URL" 9 | .br 10 | .SH "AUTHOR" 11 | This program and manual page was written by Radim Kolar, 12 | for the 13 | .B Supreme Personality of Godhead 14 | (but may be used by others). 15 | .SH "DESCRIPTION" 16 | .B webbench 17 | is simple program for benchmarking HTTP servers or any 18 | other servers, which can be accessed via HTTP proxy. Unlike others 19 | benchmarks, 20 | .B webbench 21 | uses multiple processes for simulating traffic 22 | generated by multiple users. This allows better operating 23 | on SMP systems and on systems with slow or buggy implementation 24 | of select(). 25 | .SH OPTIONS 26 | The programs follow the usual GNU command line syntax, with long 27 | options starting with two dashes (`-'). 28 | A summary of options are included below. 29 | .TP 30 | .B \-?, \-h, \-\-help 31 | Show summary of options. 32 | .TP 33 | .B \-v, \-\-version 34 | Show version of program. 35 | .TP 36 | .B \-f, \-\-force 37 | Do not wait for any response from server. Close connection after 38 | request is send. This option produce quite a good denial of service 39 | attack. 40 | .TP 41 | .B \-9, \-\-http09 42 | Use HTTP/0.9 protocol, if possible. 43 | .TP 44 | .B \-1, \-\-http10 45 | Use HTTP/1.0 protocol, if possible. 46 | .TP 47 | .B \-2, \-\-http11 48 | Use HTTP/1.1 protocol (without 49 | .I Keep-Alive 50 | ), if possible. 51 | .TP 52 | .B \-r, \-\-reload 53 | Forces proxy to reload document. If proxy is not 54 | set, option has no effect. 55 | .TP 56 | .B \-t, \-\-time 57 | Run benchmark for 58 | .I 59 | seconds. Default value is 30. 60 | .TP 61 | .B \-p, \-\-proxy 62 | Send request via proxy server. Needed for supporting others protocols 63 | than HTTP. 64 | .TP 65 | .B \-\-get 66 | Use GET request method. 67 | .TP 68 | .B \-\-head 69 | Use HEAD request method. 70 | .TP 71 | .B \-\-options 72 | Use OPTIONS request method. 73 | .TP 74 | .B \-\-trace 75 | Use TRACE request method. 76 | .TP 77 | .B \-c, \-\-clients 78 | Use 79 | .I 80 | multiple clients for benchmark. Default value 81 | is 1. 82 | .SH "EXIT STATUS" 83 | .TP 84 | 0 - sucess 85 | .TP 86 | 1 - benchmark failed, can not connect to server 87 | .TP 88 | 2 - bad command line argument(s) 89 | .TP 90 | 3 - internal error, i.e. fork failed 91 | .SH "TODO" 92 | Include support for using 93 | .I Keep-Alive 94 | HTTP/1.1 connections. 95 | .SH "COPYING" 96 | Webbench is distributed under GPL. Copyright 1997-2004 97 | Radim Kolar (hsn@netmag.cz). 98 | UNIX sockets code taken from popclient 1.5 4/1/94 99 | public domain code, created by Virginia Tech Computing Center. 100 | .BR 101 | This man page is public domain. 102 | -------------------------------------------------------------------------------- /test_presure/webbench-1.5/webbench.c: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Radim Kolar 1997-2004 3 | * This is free software, see GNU Public License version 2 for 4 | * details. 5 | * 6 | * Simple forking WWW Server benchmark: 7 | * 8 | * Usage: 9 | * webbench --help 10 | * 11 | * Return codes: 12 | * 0 - sucess 13 | * 1 - benchmark failed (server is not on-line) 14 | * 2 - bad param 15 | * 3 - internal error, fork failed 16 | * 17 | */ 18 | #include "socket.c" 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | /* values */ 28 | volatile int timerexpired=0; 29 | int speed=0; 30 | int failed=0; 31 | int bytes=0; 32 | /* globals */ 33 | int http10=1; /* 0 - http/0.9, 1 - http/1.0, 2 - http/1.1 */ 34 | /* Allow: GET, HEAD, OPTIONS, TRACE */ 35 | #define METHOD_GET 0 36 | #define METHOD_HEAD 1 37 | #define METHOD_OPTIONS 2 38 | #define METHOD_TRACE 3 39 | #define PROGRAM_VERSION "1.5" 40 | int method=METHOD_GET; 41 | int clients=1; 42 | int force=0; 43 | int force_reload=0; 44 | int proxyport=80; 45 | char *proxyhost=NULL; 46 | int benchtime=30; 47 | /* internal */ 48 | int mypipe[2]; 49 | char host[MAXHOSTNAMELEN]; 50 | #define REQUEST_SIZE 2048 51 | char request[REQUEST_SIZE]; 52 | 53 | static const struct option long_options[]= 54 | { 55 | {"force",no_argument,&force,1}, 56 | {"reload",no_argument,&force_reload,1}, 57 | {"time",required_argument,NULL,'t'}, 58 | {"help",no_argument,NULL,'?'}, 59 | {"http09",no_argument,NULL,'9'}, 60 | {"http10",no_argument,NULL,'1'}, 61 | {"http11",no_argument,NULL,'2'}, 62 | {"get",no_argument,&method,METHOD_GET}, 63 | {"head",no_argument,&method,METHOD_HEAD}, 64 | {"options",no_argument,&method,METHOD_OPTIONS}, 65 | {"trace",no_argument,&method,METHOD_TRACE}, 66 | {"version",no_argument,NULL,'V'}, 67 | {"proxy",required_argument,NULL,'p'}, 68 | {"clients",required_argument,NULL,'c'}, 69 | {NULL,0,NULL,0} 70 | }; 71 | 72 | /* prototypes */ 73 | static void benchcore(const char* host,const int port, const char *request); 74 | static int bench(void); 75 | static void build_request(const char *url); 76 | 77 | static void alarm_handler(int signal) 78 | { 79 | timerexpired=1; 80 | } 81 | 82 | static void usage(void) 83 | { 84 | fprintf(stderr, 85 | "webbench [option]... URL\n" 86 | " -f|--force Don't wait for reply from server.\n" 87 | " -r|--reload Send reload request - Pragma: no-cache.\n" 88 | " -t|--time Run benchmark for seconds. Default 30.\n" 89 | " -p|--proxy Use proxy server for request.\n" 90 | " -c|--clients Run HTTP clients at once. Default one.\n" 91 | " -9|--http09 Use HTTP/0.9 style requests.\n" 92 | " -1|--http10 Use HTTP/1.0 protocol.\n" 93 | " -2|--http11 Use HTTP/1.1 protocol.\n" 94 | " --get Use GET request method.\n" 95 | " --head Use HEAD request method.\n" 96 | " --options Use OPTIONS request method.\n" 97 | " --trace Use TRACE request method.\n" 98 | " -?|-h|--help This information.\n" 99 | " -V|--version Display program version.\n" 100 | ); 101 | }; 102 | int main(int argc, char *argv[]) 103 | { 104 | int opt=0; 105 | int options_index=0; 106 | char *tmp=NULL; 107 | 108 | if(argc==1) 109 | { 110 | usage(); 111 | return 2; 112 | } 113 | 114 | while((opt=getopt_long(argc,argv,"912Vfrt:p:c:?h",long_options,&options_index))!=EOF ) 115 | { 116 | switch(opt) 117 | { 118 | case 0 : break; 119 | case 'f': force=1;break; 120 | case 'r': force_reload=1;break; 121 | case '9': http10=0;break; 122 | case '1': http10=1;break; 123 | case '2': http10=2;break; 124 | case 'V': printf(PROGRAM_VERSION"\n");exit(0); 125 | case 't': benchtime=atoi(optarg);break; 126 | case 'p': 127 | /* proxy server parsing server:port */ 128 | tmp=strrchr(optarg,':'); 129 | proxyhost=optarg; 130 | if(tmp==NULL) 131 | { 132 | break; 133 | } 134 | if(tmp==optarg) 135 | { 136 | fprintf(stderr,"Error in option --proxy %s: Missing hostname.\n",optarg); 137 | return 2; 138 | } 139 | if(tmp==optarg+strlen(optarg)-1) 140 | { 141 | fprintf(stderr,"Error in option --proxy %s Port number is missing.\n",optarg); 142 | return 2; 143 | } 144 | *tmp='\0'; 145 | proxyport=atoi(tmp+1);break; 146 | case ':': 147 | case 'h': 148 | case '?': usage();return 2;break; 149 | case 'c': clients=atoi(optarg);break; 150 | } 151 | } 152 | 153 | if(optind==argc) { 154 | fprintf(stderr,"webbench: Missing URL!\n"); 155 | usage(); 156 | return 2; 157 | } 158 | 159 | if(clients==0) clients=1; 160 | if(benchtime==0) benchtime=60; 161 | /* Copyright */ 162 | fprintf(stderr,"Webbench - Simple Web Benchmark "PROGRAM_VERSION"\n" 163 | "Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.\n" 164 | ); 165 | build_request(argv[optind]); 166 | /* print bench info */ 167 | printf("\nBenchmarking: "); 168 | switch(method) 169 | { 170 | case METHOD_GET: 171 | default: 172 | printf("GET");break; 173 | case METHOD_OPTIONS: 174 | printf("OPTIONS");break; 175 | case METHOD_HEAD: 176 | printf("HEAD");break; 177 | case METHOD_TRACE: 178 | printf("TRACE");break; 179 | } 180 | printf(" %s",argv[optind]); 181 | switch(http10) 182 | { 183 | case 0: printf(" (using HTTP/0.9)");break; 184 | case 2: printf(" (using HTTP/1.1)");break; 185 | } 186 | printf("\n"); 187 | if(clients==1) printf("1 client"); 188 | else 189 | printf("%d clients",clients); 190 | 191 | printf(", running %d sec", benchtime); 192 | if(force) printf(", early socket close"); 193 | if(proxyhost!=NULL) printf(", via proxy server %s:%d",proxyhost,proxyport); 194 | if(force_reload) printf(", forcing reload"); 195 | printf(".\n"); 196 | return bench(); 197 | } 198 | 199 | void build_request(const char *url) 200 | { 201 | char tmp[10]; 202 | int i; 203 | 204 | bzero(host,MAXHOSTNAMELEN); 205 | bzero(request,REQUEST_SIZE); 206 | 207 | if(force_reload && proxyhost!=NULL && http10<1) http10=1; 208 | if(method==METHOD_HEAD && http10<1) http10=1; 209 | if(method==METHOD_OPTIONS && http10<2) http10=2; 210 | if(method==METHOD_TRACE && http10<2) http10=2; 211 | 212 | switch(method) 213 | { 214 | default: 215 | case METHOD_GET: strcpy(request,"GET");break; 216 | case METHOD_HEAD: strcpy(request,"HEAD");break; 217 | case METHOD_OPTIONS: strcpy(request,"OPTIONS");break; 218 | case METHOD_TRACE: strcpy(request,"TRACE");break; 219 | } 220 | 221 | strcat(request," "); 222 | 223 | if(NULL==strstr(url,"://")) 224 | { 225 | fprintf(stderr, "\n%s: is not a valid URL.\n",url); 226 | exit(2); 227 | } 228 | if(strlen(url)>1500) 229 | { 230 | fprintf(stderr,"URL is too long.\n"); 231 | exit(2); 232 | } 233 | if(proxyhost==NULL) 234 | if (0!=strncasecmp("http://",url,7)) 235 | { fprintf(stderr,"\nOnly HTTP protocol is directly supported, set --proxy for others.\n"); 236 | exit(2); 237 | } 238 | /* protocol/host delimiter */ 239 | i=strstr(url,"://")-url+3; 240 | /* printf("%d\n",i); */ 241 | 242 | if(strchr(url+i,'/')==NULL) { 243 | fprintf(stderr,"\nInvalid URL syntax - hostname don't ends with '/'.\n"); 244 | exit(2); 245 | } 246 | if(proxyhost==NULL) 247 | { 248 | /* get port from hostname */ 249 | if(index(url+i,':')!=NULL && 250 | index(url+i,':')0) 275 | strcat(request,"User-Agent: WebBench "PROGRAM_VERSION"\r\n"); 276 | if(proxyhost==NULL && http10>0) 277 | { 278 | strcat(request,"Host: "); 279 | strcat(request,host); 280 | strcat(request,"\r\n"); 281 | } 282 | if(force_reload && proxyhost!=NULL) 283 | { 284 | strcat(request,"Pragma: no-cache\r\n"); 285 | } 286 | if(http10>1) 287 | strcat(request,"Connection: close\r\n"); 288 | /* add empty line at end */ 289 | if(http10>0) strcat(request,"\r\n"); 290 | // printf("Req=%s\n",request); 291 | } 292 | 293 | /* vraci system rc error kod */ 294 | static int bench(void) 295 | { 296 | int i,j,k; 297 | pid_t pid=0; 298 | FILE *f; 299 | 300 | /* check avaibility of target server */ 301 | i=Socket(proxyhost==NULL?host:proxyhost,proxyport); 302 | if(i<0) { 303 | fprintf(stderr,"\nConnect to server failed. Aborting benchmark.\n"); 304 | return 1; 305 | } 306 | close(i); 307 | /* create pipe */ 308 | if(pipe(mypipe)) 309 | { 310 | perror("pipe failed."); 311 | return 3; 312 | } 313 | 314 | /* not needed, since we have alarm() in childrens */ 315 | /* wait 4 next system clock tick */ 316 | /* 317 | cas=time(NULL); 318 | while(time(NULL)==cas) 319 | sched_yield(); 320 | */ 321 | 322 | /* fork childs */ 323 | for(i=0;i0) 418 | { 419 | /* fprintf(stderr,"Correcting failed by signal\n"); */ 420 | failed--; 421 | } 422 | return; 423 | } 424 | s=Socket(host,port); 425 | if(s<0) { failed++;continue;} 426 | if(rlen!=write(s,req,rlen)) {failed++;close(s);continue;} 427 | if(http10==0) 428 | if(shutdown(s,1)) { failed++;close(s);continue;} 429 | if(force==0) 430 | { 431 | /* read all available data from socket */ 432 | while(1) 433 | { 434 | if(timerexpired) break; 435 | i=read(s,buf,1500); 436 | /* fprintf(stderr,"%d\n",i); */ 437 | if(i<0) 438 | { 439 | failed++; 440 | close(s); 441 | goto nexttry; 442 | } 443 | else 444 | if(i==0) break; 445 | else 446 | bytes+=i; 447 | } 448 | } 449 | if(close(s)) {failed++;continue;} 450 | speed++; 451 | } 452 | } 453 | -------------------------------------------------------------------------------- /test_presure/webbench-1.5/webbench.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yoka416/TinyWebServer/96689cd810b409ecf7591afab82a4bcef95dfecf/test_presure/webbench-1.5/webbench.o -------------------------------------------------------------------------------- /threadpool/README.md: -------------------------------------------------------------------------------- 1 | 2 | 半同步/半反应堆线程池 3 | =============== 4 | 使用一个工作队列完全解除了主线程和工作线程的耦合关系:主线程往工作队列中插入任务,工作线程通过竞争来取得任务并执行它。 5 | > * 同步I/O模拟proactor模式 6 | > * 半同步/半反应堆 7 | > * 线程池 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /threadpool/threadpool.h: -------------------------------------------------------------------------------- 1 | #ifndef THREADPOOL_H 2 | #define THREADPOOL_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "../lock/locker.h" 9 | #include "../CGImysql/sql_connection_pool.h" 10 | 11 | template 12 | class threadpool 13 | { 14 | public: 15 | /*thread_number是线程池中线程的数量,max_requests是请求队列中最多允许的、等待处理的请求的数量*/ 16 | threadpool(int actor_model, connection_pool *connPool, int thread_number = 8, int max_request = 10000); 17 | ~threadpool(); 18 | bool append(T *request, int state); 19 | bool append_p(T *request); 20 | 21 | private: 22 | /*工作线程运行的函数,它不断从工作队列中取出任务并执行之*/ 23 | static void *worker(void *arg); 24 | void run(); 25 | 26 | private: 27 | int m_thread_number; //线程池中的线程数 28 | int m_max_requests; //请求队列中允许的最大请求数 29 | pthread_t *m_threads; //描述线程池的数组,其大小为m_thread_number 30 | std::list m_workqueue; //请求队列 31 | locker m_queuelocker; //保护请求队列的互斥锁 32 | sem m_queuestat; //是否有任务需要处理 33 | connection_pool *m_connPool; //数据库 34 | int m_actor_model; //模型切换 35 | }; 36 | template 37 | threadpool::threadpool( int actor_model, connection_pool *connPool, int thread_number, int max_requests) : m_actor_model(actor_model),m_thread_number(thread_number), m_max_requests(max_requests), m_threads(NULL),m_connPool(connPool) 38 | { 39 | if (thread_number <= 0 || max_requests <= 0) 40 | throw std::exception(); 41 | m_threads = new pthread_t[m_thread_number]; 42 | if (!m_threads) 43 | throw std::exception(); 44 | for (int i = 0; i < thread_number; ++i) 45 | { 46 | if (pthread_create(m_threads + i, NULL, worker, this) != 0) 47 | { 48 | delete[] m_threads; 49 | throw std::exception(); 50 | } 51 | if (pthread_detach(m_threads[i])) 52 | { 53 | delete[] m_threads; 54 | throw std::exception(); 55 | } 56 | } 57 | } 58 | template 59 | threadpool::~threadpool() 60 | { 61 | delete[] m_threads; 62 | } 63 | template 64 | bool threadpool::append(T *request, int state) 65 | { 66 | m_queuelocker.lock(); 67 | if (m_workqueue.size() >= m_max_requests) 68 | { 69 | m_queuelocker.unlock(); 70 | return false; 71 | } 72 | request->m_state = state; 73 | m_workqueue.push_back(request); 74 | m_queuelocker.unlock(); 75 | m_queuestat.post(); 76 | return true; 77 | } 78 | template 79 | bool threadpool::append_p(T *request) 80 | { 81 | m_queuelocker.lock(); 82 | if (m_workqueue.size() >= m_max_requests) 83 | { 84 | m_queuelocker.unlock(); 85 | return false; 86 | } 87 | m_workqueue.push_back(request); 88 | m_queuelocker.unlock(); 89 | m_queuestat.post(); 90 | return true; 91 | } 92 | template 93 | void *threadpool::worker(void *arg) 94 | { 95 | threadpool *pool = (threadpool *)arg; 96 | pool->run(); 97 | return pool; 98 | } 99 | template 100 | void threadpool::run() 101 | { 102 | while (true) 103 | { 104 | m_queuestat.wait(); 105 | m_queuelocker.lock(); 106 | if (m_workqueue.empty()) 107 | { 108 | m_queuelocker.unlock(); 109 | continue; 110 | } 111 | T *request = m_workqueue.front(); 112 | m_workqueue.pop_front(); 113 | m_queuelocker.unlock(); 114 | if (!request) 115 | continue; 116 | if (1 == m_actor_model) 117 | { 118 | if (0 == request->m_state) 119 | { 120 | if (request->read_once()) 121 | { 122 | request->improv = 1; 123 | connectionRAII mysqlcon(&request->mysql, m_connPool); 124 | request->process(); 125 | } 126 | else 127 | { 128 | request->improv = 1; 129 | request->timer_flag = 1; 130 | } 131 | } 132 | else 133 | { 134 | if (request->write()) 135 | { 136 | request->improv = 1; 137 | } 138 | else 139 | { 140 | request->improv = 1; 141 | request->timer_flag = 1; 142 | } 143 | } 144 | } 145 | else 146 | { 147 | connectionRAII mysqlcon(&request->mysql, m_connPool); 148 | request->process(); 149 | } 150 | } 151 | } 152 | #endif 153 | -------------------------------------------------------------------------------- /timer/README.md: -------------------------------------------------------------------------------- 1 | 2 | 定时器处理非活动连接 3 | =============== 4 | 由于非活跃连接占用了连接资源,严重影响服务器的性能,通过实现一个服务器定时器,处理这种非活跃连接,释放连接资源。利用alarm函数周期性地触发SIGALRM信号,该信号的信号处理函数利用管道通知主循环执行定时器链表上的定时任务. 5 | > * 统一事件源 6 | > * 基于升序链表的定时器 7 | > * 处理非活动连接 8 | -------------------------------------------------------------------------------- /timer/lst_timer.cpp: -------------------------------------------------------------------------------- 1 | #include "lst_timer.h" 2 | #include "../http/http_conn.h" 3 | 4 | sort_timer_lst::sort_timer_lst() 5 | { 6 | head = NULL; 7 | tail = NULL; 8 | } 9 | sort_timer_lst::~sort_timer_lst() 10 | { 11 | util_timer *tmp = head; 12 | while (tmp) 13 | { 14 | head = tmp->next; 15 | delete tmp; 16 | tmp = head; 17 | } 18 | } 19 | 20 | void sort_timer_lst::add_timer(util_timer *timer) 21 | { 22 | if (!timer) 23 | { 24 | return; 25 | } 26 | if (!head) 27 | { 28 | head = tail = timer; 29 | return; 30 | } 31 | if (timer->expire < head->expire) 32 | { 33 | timer->next = head; 34 | head->prev = timer; 35 | head = timer; 36 | return; 37 | } 38 | add_timer(timer, head); 39 | } 40 | void sort_timer_lst::adjust_timer(util_timer *timer) 41 | { 42 | if (!timer) 43 | { 44 | return; 45 | } 46 | util_timer *tmp = timer->next; 47 | if (!tmp || (timer->expire < tmp->expire)) 48 | { 49 | return; 50 | } 51 | if (timer == head) 52 | { 53 | head = head->next; 54 | head->prev = NULL; 55 | timer->next = NULL; 56 | add_timer(timer, head); 57 | } 58 | else 59 | { 60 | timer->prev->next = timer->next; 61 | timer->next->prev = timer->prev; 62 | add_timer(timer, timer->next); 63 | } 64 | } 65 | void sort_timer_lst::del_timer(util_timer *timer) 66 | { 67 | if (!timer) 68 | { 69 | return; 70 | } 71 | if ((timer == head) && (timer == tail)) 72 | { 73 | delete timer; 74 | head = NULL; 75 | tail = NULL; 76 | return; 77 | } 78 | if (timer == head) 79 | { 80 | head = head->next; 81 | head->prev = NULL; 82 | delete timer; 83 | return; 84 | } 85 | if (timer == tail) 86 | { 87 | tail = tail->prev; 88 | tail->next = NULL; 89 | delete timer; 90 | return; 91 | } 92 | timer->prev->next = timer->next; 93 | timer->next->prev = timer->prev; 94 | delete timer; 95 | } 96 | void sort_timer_lst::tick() 97 | { 98 | if (!head) 99 | { 100 | return; 101 | } 102 | 103 | time_t cur = time(NULL); 104 | util_timer *tmp = head; 105 | while (tmp) 106 | { 107 | if (cur < tmp->expire) 108 | { 109 | break; 110 | } 111 | tmp->cb_func(tmp->user_data); 112 | head = tmp->next; 113 | if (head) 114 | { 115 | head->prev = NULL; 116 | } 117 | delete tmp; 118 | tmp = head; 119 | } 120 | } 121 | 122 | void sort_timer_lst::add_timer(util_timer *timer, util_timer *lst_head) 123 | { 124 | util_timer *prev = lst_head; 125 | util_timer *tmp = prev->next; 126 | while (tmp) 127 | { 128 | if (timer->expire < tmp->expire) 129 | { 130 | prev->next = timer; 131 | timer->next = tmp; 132 | tmp->prev = timer; 133 | timer->prev = prev; 134 | break; 135 | } 136 | prev = tmp; 137 | tmp = tmp->next; 138 | } 139 | if (!tmp) 140 | { 141 | prev->next = timer; 142 | timer->prev = prev; 143 | timer->next = NULL; 144 | tail = timer; 145 | } 146 | } 147 | 148 | void Utils::init(int timeslot) 149 | { 150 | m_TIMESLOT = timeslot; 151 | } 152 | 153 | //对文件描述符设置非阻塞 154 | int Utils::setnonblocking(int fd) 155 | { 156 | int old_option = fcntl(fd, F_GETFL); 157 | int new_option = old_option | O_NONBLOCK; 158 | fcntl(fd, F_SETFL, new_option); 159 | return old_option; 160 | } 161 | 162 | //将内核事件表注册读事件,ET模式,选择开启EPOLLONESHOT 163 | void Utils::addfd(int epollfd, int fd, bool one_shot, int TRIGMode) 164 | { 165 | epoll_event event; 166 | event.data.fd = fd; 167 | 168 | if (1 == TRIGMode) 169 | event.events = EPOLLIN | EPOLLET | EPOLLRDHUP; 170 | else 171 | event.events = EPOLLIN | EPOLLRDHUP; 172 | 173 | if (one_shot) 174 | event.events |= EPOLLONESHOT; 175 | epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event); 176 | setnonblocking(fd); 177 | } 178 | 179 | //信号处理函数 180 | void Utils::sig_handler(int sig) 181 | { 182 | //为保证函数的可重入性,保留原来的errno 183 | int save_errno = errno; 184 | int msg = sig; 185 | send(u_pipefd[1], (char *)&msg, 1, 0); 186 | errno = save_errno; 187 | } 188 | 189 | //设置信号函数 190 | void Utils::addsig(int sig, void(handler)(int), bool restart) 191 | { 192 | struct sigaction sa; 193 | memset(&sa, '\0', sizeof(sa)); 194 | sa.sa_handler = handler; 195 | if (restart) 196 | sa.sa_flags |= SA_RESTART; 197 | sigfillset(&sa.sa_mask); 198 | assert(sigaction(sig, &sa, NULL) != -1); 199 | } 200 | 201 | //定时处理任务,重新定时以不断触发SIGALRM信号 202 | void Utils::timer_handler() 203 | { 204 | m_timer_lst.tick(); 205 | alarm(m_TIMESLOT); 206 | } 207 | 208 | void Utils::show_error(int connfd, const char *info) 209 | { 210 | send(connfd, info, strlen(info), 0); 211 | close(connfd); 212 | } 213 | 214 | int *Utils::u_pipefd = 0; 215 | int Utils::u_epollfd = 0; 216 | 217 | class Utils; 218 | void cb_func(client_data *user_data) 219 | { 220 | epoll_ctl(Utils::u_epollfd, EPOLL_CTL_DEL, user_data->sockfd, 0); 221 | assert(user_data); 222 | close(user_data->sockfd); 223 | http_conn::m_user_count--; 224 | } 225 | -------------------------------------------------------------------------------- /timer/lst_timer.h: -------------------------------------------------------------------------------- 1 | #ifndef LST_TIMER 2 | #define LST_TIMER 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | #include 25 | #include "../log/log.h" 26 | 27 | class util_timer; 28 | 29 | struct client_data 30 | { 31 | sockaddr_in address; 32 | int sockfd; 33 | util_timer *timer; 34 | }; 35 | 36 | class util_timer 37 | { 38 | public: 39 | util_timer() : prev(NULL), next(NULL) {} 40 | 41 | public: 42 | time_t expire; 43 | 44 | void (* cb_func)(client_data *); 45 | client_data *user_data; 46 | util_timer *prev; 47 | util_timer *next; 48 | }; 49 | 50 | class sort_timer_lst 51 | { 52 | public: 53 | sort_timer_lst(); 54 | ~sort_timer_lst(); 55 | 56 | void add_timer(util_timer *timer); 57 | void adjust_timer(util_timer *timer); 58 | void del_timer(util_timer *timer); 59 | void tick(); 60 | 61 | private: 62 | void add_timer(util_timer *timer, util_timer *lst_head); 63 | 64 | util_timer *head; 65 | util_timer *tail; 66 | }; 67 | 68 | class Utils 69 | { 70 | public: 71 | Utils() {} 72 | ~Utils() {} 73 | 74 | void init(int timeslot); 75 | 76 | //对文件描述符设置非阻塞 77 | int setnonblocking(int fd); 78 | 79 | //将内核事件表注册读事件,ET模式,选择开启EPOLLONESHOT 80 | void addfd(int epollfd, int fd, bool one_shot, int TRIGMode); 81 | 82 | //信号处理函数 83 | static void sig_handler(int sig); 84 | 85 | //设置信号函数 86 | void addsig(int sig, void(handler)(int), bool restart = true); 87 | 88 | //定时处理任务,重新定时以不断触发SIGALRM信号 89 | void timer_handler(); 90 | 91 | void show_error(int connfd, const char *info); 92 | 93 | public: 94 | static int *u_pipefd; 95 | sort_timer_lst m_timer_lst; 96 | static int u_epollfd; 97 | int m_TIMESLOT; 98 | }; 99 | 100 | void cb_func(client_data *user_data); 101 | 102 | #endif 103 | -------------------------------------------------------------------------------- /webserver.cpp: -------------------------------------------------------------------------------- 1 | #include "webserver.h" 2 | 3 | WebServer::WebServer() 4 | { 5 | //http_conn类对象 6 | users = new http_conn[MAX_FD]; 7 | 8 | //root文件夹路径 9 | char server_path[200]; 10 | getcwd(server_path, 200); 11 | char root[6] = "/root"; 12 | m_root = (char *)malloc(strlen(server_path) + strlen(root) + 1); 13 | strcpy(m_root, server_path); 14 | strcat(m_root, root); 15 | 16 | //定时器 17 | users_timer = new client_data[MAX_FD]; 18 | } 19 | 20 | WebServer::~WebServer() 21 | { 22 | close(m_epollfd); 23 | close(m_listenfd); 24 | close(m_pipefd[1]); 25 | close(m_pipefd[0]); 26 | delete[] users; 27 | delete[] users_timer; 28 | delete m_pool; 29 | } 30 | 31 | void WebServer::init(int port, string user, string passWord, string databaseName, int log_write, 32 | int opt_linger, int trigmode, int sql_num, int thread_num, int close_log, int actor_model) 33 | { 34 | m_port = port; 35 | m_user = user; 36 | m_passWord = passWord; 37 | m_databaseName = databaseName; 38 | m_sql_num = sql_num; 39 | m_thread_num = thread_num; 40 | m_log_write = log_write; 41 | m_OPT_LINGER = opt_linger; 42 | m_TRIGMode = trigmode; 43 | m_close_log = close_log; 44 | m_actormodel = actor_model; 45 | } 46 | 47 | void WebServer::trig_mode() 48 | { 49 | //LT + LT 50 | if (0 == m_TRIGMode) 51 | { 52 | m_LISTENTrigmode = 0; 53 | m_CONNTrigmode = 0; 54 | } 55 | //LT + ET 56 | else if (1 == m_TRIGMode) 57 | { 58 | m_LISTENTrigmode = 0; 59 | m_CONNTrigmode = 1; 60 | } 61 | //ET + LT 62 | else if (2 == m_TRIGMode) 63 | { 64 | m_LISTENTrigmode = 1; 65 | m_CONNTrigmode = 0; 66 | } 67 | //ET + ET 68 | else if (3 == m_TRIGMode) 69 | { 70 | m_LISTENTrigmode = 1; 71 | m_CONNTrigmode = 1; 72 | } 73 | } 74 | 75 | void WebServer::log_write() 76 | { 77 | if (0 == m_close_log) 78 | { 79 | //初始化日志 80 | if (1 == m_log_write) 81 | Log::get_instance()->init("./ServerLog", m_close_log, 2000, 800000, 800); 82 | else 83 | Log::get_instance()->init("./ServerLog", m_close_log, 2000, 800000, 0); 84 | } 85 | } 86 | 87 | void WebServer::sql_pool() 88 | { 89 | //初始化数据库连接池 90 | m_connPool = connection_pool::GetInstance(); 91 | m_connPool->init("localhost", m_user, m_passWord, m_databaseName, 3306, m_sql_num, m_close_log); 92 | 93 | //初始化数据库读取表 94 | users->initmysql_result(m_connPool); 95 | } 96 | 97 | void WebServer::thread_pool() 98 | { 99 | //线程池 100 | m_pool = new threadpool(m_actormodel, m_connPool, m_thread_num); 101 | } 102 | 103 | void WebServer::eventListen() 104 | { 105 | //网络编程基础步骤 106 | m_listenfd = socket(PF_INET, SOCK_STREAM, 0); 107 | assert(m_listenfd >= 0); 108 | 109 | //优雅关闭连接 110 | if (0 == m_OPT_LINGER) 111 | { 112 | struct linger tmp = {0, 1}; 113 | setsockopt(m_listenfd, SOL_SOCKET, SO_LINGER, &tmp, sizeof(tmp)); 114 | } 115 | else if (1 == m_OPT_LINGER) 116 | { 117 | struct linger tmp = {1, 1}; 118 | setsockopt(m_listenfd, SOL_SOCKET, SO_LINGER, &tmp, sizeof(tmp)); 119 | } 120 | 121 | int ret = 0; 122 | struct sockaddr_in address; 123 | bzero(&address, sizeof(address)); 124 | address.sin_family = AF_INET; 125 | address.sin_addr.s_addr = htonl(INADDR_ANY); 126 | address.sin_port = htons(m_port); 127 | 128 | int flag = 1; 129 | setsockopt(m_listenfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); 130 | ret = bind(m_listenfd, (struct sockaddr *)&address, sizeof(address)); 131 | assert(ret >= 0); 132 | ret = listen(m_listenfd, 5); 133 | assert(ret >= 0); 134 | 135 | utils.init(TIMESLOT); 136 | 137 | //epoll创建内核事件表 138 | epoll_event events[MAX_EVENT_NUMBER]; 139 | m_epollfd = epoll_create(5); 140 | assert(m_epollfd != -1); 141 | 142 | utils.addfd(m_epollfd, m_listenfd, false, m_LISTENTrigmode); 143 | http_conn::m_epollfd = m_epollfd; 144 | 145 | ret = socketpair(PF_UNIX, SOCK_STREAM, 0, m_pipefd); 146 | assert(ret != -1); 147 | utils.setnonblocking(m_pipefd[1]); 148 | utils.addfd(m_epollfd, m_pipefd[0], false, 0); 149 | 150 | utils.addsig(SIGPIPE, SIG_IGN); 151 | utils.addsig(SIGALRM, utils.sig_handler, false); 152 | utils.addsig(SIGTERM, utils.sig_handler, false); 153 | 154 | alarm(TIMESLOT); 155 | 156 | //工具类,信号和描述符基础操作 157 | Utils::u_pipefd = m_pipefd; 158 | Utils::u_epollfd = m_epollfd; 159 | } 160 | 161 | void WebServer::timer(int connfd, struct sockaddr_in client_address) 162 | { 163 | users[connfd].init(connfd, client_address, m_root, m_CONNTrigmode, m_close_log, m_user, m_passWord, m_databaseName); 164 | 165 | //初始化client_data数据 166 | //创建定时器,设置回调函数和超时时间,绑定用户数据,将定时器添加到链表中 167 | users_timer[connfd].address = client_address; 168 | users_timer[connfd].sockfd = connfd; 169 | util_timer *timer = new util_timer; 170 | timer->user_data = &users_timer[connfd]; 171 | timer->cb_func = cb_func; 172 | time_t cur = time(NULL); 173 | timer->expire = cur + 3 * TIMESLOT; 174 | users_timer[connfd].timer = timer; 175 | utils.m_timer_lst.add_timer(timer); 176 | } 177 | 178 | //若有数据传输,则将定时器往后延迟3个单位 179 | //并对新的定时器在链表上的位置进行调整 180 | void WebServer::adjust_timer(util_timer *timer) 181 | { 182 | time_t cur = time(NULL); 183 | timer->expire = cur + 3 * TIMESLOT; 184 | utils.m_timer_lst.adjust_timer(timer); 185 | 186 | LOG_INFO("%s", "adjust timer once"); 187 | } 188 | 189 | void WebServer::deal_timer(util_timer *timer, int sockfd) 190 | { 191 | timer->cb_func(&users_timer[sockfd]); 192 | if (timer) 193 | { 194 | utils.m_timer_lst.del_timer(timer); 195 | } 196 | 197 | LOG_INFO("close fd %d", users_timer[sockfd].sockfd); 198 | } 199 | 200 | bool WebServer::dealclinetdata() 201 | { 202 | struct sockaddr_in client_address; 203 | socklen_t client_addrlength = sizeof(client_address); 204 | if (0 == m_LISTENTrigmode) 205 | { 206 | int connfd = accept(m_listenfd, (struct sockaddr *)&client_address, &client_addrlength); 207 | if (connfd < 0) 208 | { 209 | LOG_ERROR("%s:errno is:%d", "accept error", errno); 210 | return false; 211 | } 212 | if (http_conn::m_user_count >= MAX_FD) 213 | { 214 | utils.show_error(connfd, "Internal server busy"); 215 | LOG_ERROR("%s", "Internal server busy"); 216 | return false; 217 | } 218 | timer(connfd, client_address); 219 | } 220 | 221 | else 222 | { 223 | while (1) 224 | { 225 | int connfd = accept(m_listenfd, (struct sockaddr *)&client_address, &client_addrlength); 226 | if (connfd < 0) 227 | { 228 | LOG_ERROR("%s:errno is:%d", "accept error", errno); 229 | break; 230 | } 231 | if (http_conn::m_user_count >= MAX_FD) 232 | { 233 | utils.show_error(connfd, "Internal server busy"); 234 | LOG_ERROR("%s", "Internal server busy"); 235 | break; 236 | } 237 | timer(connfd, client_address); 238 | } 239 | return false; 240 | } 241 | return true; 242 | } 243 | 244 | bool WebServer::dealwithsignal(bool &timeout, bool &stop_server) 245 | { 246 | int ret = 0; 247 | int sig; 248 | char signals[1024]; 249 | ret = recv(m_pipefd[0], signals, sizeof(signals), 0); 250 | if (ret == -1) 251 | { 252 | return false; 253 | } 254 | else if (ret == 0) 255 | { 256 | return false; 257 | } 258 | else 259 | { 260 | for (int i = 0; i < ret; ++i) 261 | { 262 | switch (signals[i]) 263 | { 264 | case SIGALRM: 265 | { 266 | timeout = true; 267 | break; 268 | } 269 | case SIGTERM: 270 | { 271 | stop_server = true; 272 | break; 273 | } 274 | } 275 | } 276 | } 277 | return true; 278 | } 279 | 280 | void WebServer::dealwithread(int sockfd) 281 | { 282 | util_timer *timer = users_timer[sockfd].timer; 283 | 284 | //reactor 285 | if (1 == m_actormodel) 286 | { 287 | if (timer) 288 | { 289 | adjust_timer(timer); 290 | } 291 | 292 | //若监测到读事件,将该事件放入请求队列 293 | m_pool->append(users + sockfd, 0); 294 | 295 | while (true) 296 | { 297 | if (1 == users[sockfd].improv) 298 | { 299 | if (1 == users[sockfd].timer_flag) 300 | { 301 | deal_timer(timer, sockfd); 302 | users[sockfd].timer_flag = 0; 303 | } 304 | users[sockfd].improv = 0; 305 | break; 306 | } 307 | } 308 | } 309 | else 310 | { 311 | //proactor 312 | if (users[sockfd].read_once()) 313 | { 314 | LOG_INFO("deal with the client(%s)", inet_ntoa(users[sockfd].get_address()->sin_addr)); 315 | 316 | //若监测到读事件,将该事件放入请求队列 317 | m_pool->append_p(users + sockfd); 318 | 319 | if (timer) 320 | { 321 | adjust_timer(timer); 322 | } 323 | } 324 | else 325 | { 326 | deal_timer(timer, sockfd); 327 | } 328 | } 329 | } 330 | 331 | void WebServer::dealwithwrite(int sockfd) 332 | { 333 | util_timer *timer = users_timer[sockfd].timer; 334 | //reactor 335 | if (1 == m_actormodel) 336 | { 337 | if (timer) 338 | { 339 | adjust_timer(timer); 340 | } 341 | 342 | m_pool->append(users + sockfd, 1); 343 | 344 | while (true) 345 | { 346 | if (1 == users[sockfd].improv) 347 | { 348 | if (1 == users[sockfd].timer_flag) 349 | { 350 | deal_timer(timer, sockfd); 351 | users[sockfd].timer_flag = 0; 352 | } 353 | users[sockfd].improv = 0; 354 | break; 355 | } 356 | } 357 | } 358 | else 359 | { 360 | //proactor 361 | if (users[sockfd].write()) 362 | { 363 | LOG_INFO("send data to the client(%s)", inet_ntoa(users[sockfd].get_address()->sin_addr)); 364 | 365 | if (timer) 366 | { 367 | adjust_timer(timer); 368 | } 369 | } 370 | else 371 | { 372 | deal_timer(timer, sockfd); 373 | } 374 | } 375 | } 376 | 377 | void WebServer::eventLoop() 378 | { 379 | bool timeout = false; 380 | bool stop_server = false; 381 | 382 | while (!stop_server) 383 | { 384 | int number = epoll_wait(m_epollfd, events, MAX_EVENT_NUMBER, -1); 385 | if (number < 0 && errno != EINTR) 386 | { 387 | LOG_ERROR("%s", "epoll failure"); 388 | break; 389 | } 390 | 391 | for (int i = 0; i < number; i++) 392 | { 393 | int sockfd = events[i].data.fd; 394 | 395 | //处理新到的客户连接 396 | if (sockfd == m_listenfd) 397 | { 398 | bool flag = dealclinetdata(); 399 | if (false == flag) 400 | continue; 401 | } 402 | else if (events[i].events & (EPOLLRDHUP | EPOLLHUP | EPOLLERR)) 403 | { 404 | //服务器端关闭连接,移除对应的定时器 405 | util_timer *timer = users_timer[sockfd].timer; 406 | deal_timer(timer, sockfd); 407 | } 408 | //处理信号 409 | else if ((sockfd == m_pipefd[0]) && (events[i].events & EPOLLIN)) 410 | { 411 | bool flag = dealwithsignal(timeout, stop_server); 412 | if (false == flag) 413 | LOG_ERROR("%s", "dealclientdata failure"); 414 | } 415 | //处理客户连接上接收到的数据 416 | else if (events[i].events & EPOLLIN) 417 | { 418 | dealwithread(sockfd); 419 | } 420 | else if (events[i].events & EPOLLOUT) 421 | { 422 | dealwithwrite(sockfd); 423 | } 424 | } 425 | if (timeout) 426 | { 427 | utils.timer_handler(); 428 | 429 | LOG_INFO("%s", "timer tick"); 430 | 431 | timeout = false; 432 | } 433 | } 434 | } -------------------------------------------------------------------------------- /webserver.h: -------------------------------------------------------------------------------- 1 | #ifndef WEBSERVER_H 2 | #define WEBSERVER_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include "./threadpool/threadpool.h" 16 | #include "./http/http_conn.h" 17 | 18 | const int MAX_FD = 65536; //最大文件描述符 19 | const int MAX_EVENT_NUMBER = 10000; //最大事件数 20 | const int TIMESLOT = 5; //最小超时单位 21 | 22 | class WebServer 23 | { 24 | public: 25 | WebServer(); 26 | ~WebServer(); 27 | 28 | void init(int port , string user, string passWord, string databaseName, 29 | int log_write , int opt_linger, int trigmode, int sql_num, 30 | int thread_num, int close_log, int actor_model); 31 | 32 | void thread_pool(); 33 | void sql_pool(); 34 | void log_write(); 35 | void trig_mode(); 36 | void eventListen(); 37 | void eventLoop(); 38 | void timer(int connfd, struct sockaddr_in client_address); 39 | void adjust_timer(util_timer *timer); 40 | void deal_timer(util_timer *timer, int sockfd); 41 | bool dealclinetdata(); 42 | bool dealwithsignal(bool& timeout, bool& stop_server); 43 | void dealwithread(int sockfd); 44 | void dealwithwrite(int sockfd); 45 | 46 | public: 47 | //基础 48 | int m_port; 49 | char *m_root; 50 | int m_log_write; 51 | int m_close_log; 52 | int m_actormodel; 53 | 54 | int m_pipefd[2]; 55 | int m_epollfd; 56 | http_conn *users; 57 | 58 | //数据库相关 59 | connection_pool *m_connPool; 60 | string m_user; //登陆数据库用户名 61 | string m_passWord; //登陆数据库密码 62 | string m_databaseName; //使用数据库名 63 | int m_sql_num; 64 | 65 | //线程池相关 66 | threadpool *m_pool; 67 | int m_thread_num; 68 | 69 | //epoll_event相关 70 | epoll_event events[MAX_EVENT_NUMBER]; 71 | 72 | int m_listenfd; 73 | int m_OPT_LINGER; 74 | int m_TRIGMode; 75 | int m_LISTENTrigmode; 76 | int m_CONNTrigmode; 77 | 78 | //定时器相关 79 | client_data *users_timer; 80 | Utils utils; 81 | }; 82 | #endif 83 | --------------------------------------------------------------------------------