前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >基于c++实现简易http服务器

基于c++实现简易http服务器

原创
作者头像
手撕代码八百里
发布2023-11-22 21:57:39
4220
发布2023-11-22 21:57:39
举报
文章被收录于专栏:猿计划猿计划

前言

看到《基于c实现简易http服务器》进来的童鞋,你肯定本篇文章是使用基础的C++ 的socket来实现http服务器吧,你以为错了,使用基础的C++ 的socket来实现http服务器的文章百度一下有一大把了,我想介绍一个比较有意思的,而且实用性很强的基于C++实现建议http服务器的方案以及实现。

站在巨人的肩膀上

因为我自己做的一个项目用到了C++实现的http服务器,在做项目的时候已经考虑了很多方案例如使用httplib库等。最后还是奔着学习的角度否定了使用httplib库的方案,因为httplib库太方便了,整个httplib库就是个庞大的头文件,在之前的项目中使用过,出了问题不是太好解决,所以现在这个项目觉得自己实现一个http服务。

看到这个标题你可能会想到肯定是借助第三方库来开发的对吧。

没错。

是的。

我使用了boost库的网络库来实现http服务。

如果你没听过boost库,不知道boost库是干啥的,请看VCR:

Boost库是一个由C++社区开发的开源库集合,它提供了许多功能强大且高质量的工具和组件,用于增强C++编程语言的功能和效率。Boost库的目标是成为C++标准库的候选扩展,许多Boost组件已经被纳入C++标准。以下是Boost库的一些主要功能和作用:

  1. 泛型编程支持: Boost提供了许多模板库和工具,支持泛型编程,使得C++代码更加灵活、可重用和易于维护。
  2. 智能指针: Boost包含了shared_ptrscoped_ptr等智能指针,用于管理动态分配的内存,避免内存泄漏和提高程序的安全性。
  3. 容器和数据结构: Boost包括了一些高性能、高效的容器和数据结构,如unordered_mapmulti_index等,以及一些用于处理图、图形、堆、优先队列等的数据结构。
  4. 正则表达式库: Boost提供了一个功能强大的正则表达式库,支持Perl兼容的正则表达式语法,用于在字符串中进行模式匹配和搜索。
  5. 多线程和并发编程: Boost.Thread库提供了多线程编程的支持,包括线程的创建、同步、互斥锁、条件变量等功能。
  6. 文件系统操作: Boost.Filesystem库提供了对文件系统进行操作的工具,使得文件和目录的操作更加方便。
  7. 网络编程: Boost.Asio库提供了异步网络编程的支持,用于开发高性能的网络应用程序,包括TCP、UDP等协议。
  8. 数学和算法: Boost.Math库提供了一些数学工具,包括数值计算、特殊函数、统计函数等。
  9. 测试框架: Boost.Test库是一个用于编写和运行测试的框架,用于确保代码的质量和稳定性。
  10. 其他: Boost还包括许多其他组件,涵盖了从异常处理到元编程等广泛的领域,为C++程序员提供了强大的工具和功能。

Boost库为C++程序员提供了丰富的工具和组件,可以帮助他们更轻松地编写高效、可维护的代码,同时也推动了一些现代C++特性的发展。由于其高质量和广泛应用,Boost库的一些组件已被纳入C++标准,成为C++语言的一部分。

boost库开发环境搭建下载&编译

1、下载boost库

boost库的开源地址:https://github.com/boostorg/boost

我选择的是boost_1_55_0版本。

2、解压出来

代码语言:shell
复制
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study$ tar -zxvf boost_1_55_0.tar.gz 

3、执行./bootstrap.sh

./bootstrap.sh --prefix=pwd/_install 跟上--prefix参数即可指定安装的目录

代码语言:shell
复制
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/boost_1_55_0$ sudo ./bootstrap.sh  --prefix=`pwd`/_install
Building Boost.Build engine with toolset gcc... tools/build/v2/engine/bin.linuxx86_64/b2
Detecting Python version... 2.7
Detecting Python root... /usr
Unicode/ICU support for Boost.Regex?... /usr
Backing up existing Boost.Build configuration in project-config.jam.1
Generating Boost.Build configuration in project-config.jam...

Bootstrapping is done. To build, run:

    ./b2
    
To adjust configuration, edit 'project-config.jam'.
Further information:

   - Command line help:
     ./b2 --help
     
   - Getting started guide: 
     http://www.boost.org/more/getting_started/unix-variants.html
     
   - Boost.Build documentation:
     http://www.boost.org/boost-build2/doc/html/index.html

(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/boost_1_55_0$ 

出现如上所示提示,就说明成功了。可以继续执行b2进行编译了。

4、使用b2进行编译

代码语言:shell
复制
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/boost_1_55_0$ ./b2 --help
Boost.Build 2011.12-svn

Project-specific help:

  Project has jamfile at Jamroot

Distributed under the Boost Software License, Version 1.0.

Configuration help:

  Configuration file at
  

Distributed under the Boost Software License, Version 1.0.

Configuration help:

  Configuration file at
  

Distributed under the Boost Software License, Version 1.0. 

General command line usage:

    b2 [options] [properties] [targets]

  Options, properties and targets can be specified in any order.
      
Important Options:

  * --clean Remove targets instead of building
  * -a Rebuild everything
  * -n Don't execute the commands, only print them
  * -d+2 Show commands as they are executed
  * -d0 Supress all informational messages
  * -q Stop at first error
  * --reconfigure Rerun all configuration checks
  * --debug-configuration Diagnose configuration
  * --debug-building Report which targets are built with what properties
  * --debug-generator Diagnose generator search/execution

Further Help:

  The following options can be used to obtain additional documentation.

  * --help-options Print more obscure command line options.
  * --help-internal Boost.Build implementation details.
  * --help-doc-options Implementation details doc formatting.

...found 1 target...
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/boost_1_55_0$ 

编译

代码语言:shell
复制
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/boost_1_55_0$ ./b2 
link.jam: No such file or directory

Building the Boost C++ Libraries.


Performing configuration checks

    - 32-bit                   : no  (cached)
    - 64-bit                   : yes (cached)
    - arm                      : no  (cached)
    - mips1                    : no  (cached)
    - power                    : no  (cached)
    - sparc                    : no  (cached)
    - x86                      : yes (cached)
    - has_icu builds           : yes (cached)
warning: Graph library does not contain MPI-based parallel components.
note: to enable them, add "using mpi ;" to your user-config.jam
    - zlib                     : yes (cached)
    - iconv (libc)             : yes (cached)
    - icu                      : yes (cached)
    - lockfree boost::atomic_flag : yes (cached)
    - compiler-supports-ssse3  : yes (cached)
    - compiler-supports-avx2   : yes (cached)
    - gcc visibility           : yes (cached)
    - long double support      : yes (cached)
warning: skipping optional Message Passing Interface (MPI) library.
note: to enable MPI support, add "using mpi ;" to user-config.jam.
note: to suppress this message, pass "--without-mpi" to bjam.
note: otherwise, you can safely ignore this message.
    - zlib                     : yes (cached)

Component configuration:

    - atomic                   : building
    - chrono                   : building
    - context                  : building
    - coroutine                : building
    - date_time                : building
    - exception                : building
    - filesystem               : building
    - graph                    : building
    - graph_parallel           : building
    - iostreams                : building
    - locale                   : building
    - log                      : building
    - math                     : building
    - mpi                      : building
    - program_options          : building
    - python                   : building
    - random                   : building
    - regex                    : building
    - serialization            : building
    - signals                  : building
    - system                   : building
    - test                     : building
    - thread                   : building
    - timer                    : building
    - wave                     : building

...patience...
...patience...
...patience...

5、安装

代码语言:shell
复制
b2 install

6、查看是否安装成功

代码语言:shell
复制
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/boost_1_55_0$ ls _install/
include  lib
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/boost_1_55_0$ ls _install/include/
boost
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/boost_1_55_0$ 

学习boost库

1、访问boost库的文档(含API)

建议使用VSCode打开这个工程,整个boost的工程结构如下:

如果查看boost的文档我想这是对于初学者的必修课。

VSCode安装一个“Live Server”的插件,可以直接使用vscode运行一个web server来访问html网页资源,很方便。

可以看到目录中有index.html文件,可以点进去。

如果没打开这个live server的话,状态栏如下所示:

可以右击选择Open with List Server选项打开:

你的浏览器立马就会弹出一个窗口,十分方便。

此时状态栏也会发生变化:

当然了,你可以可以直接访问在线的boost的网站:https://www.boost.org/

2、如何找到boost的http例子

因为网络也是属于输入输出,所以必定在输入输出内。

点进去Input/Output

再点进去asio链接

可以看到Examples

点击Examples后,看到有两个案例一个是C++11 Examples,一个是C++03 Examples

这里就使用高版本的C++ 11的案例:

可以看到HTTP Server的标题,下面就是用到的文件

根据boost_asio/example/cpp11/http/server/connection.cpp可知路径在boost_asio/example/cpp11/http/server/

可以把着呢哥哥http/server/中的文件拷贝到最外层建个src目录,这样方便修改

实践boost库

在src目录中新增CMakeLists.txt文件,内容如下:

代码语言:text
复制
cmake_minimum_required(VERSION 3.20)
project(webserver)

#扫描指定目录下的源代码文件名
aux_source_directory(./ SRC_SOURCES)

include_directories(
    ./
    ../boost_1_55_0/_install/include
)

include_directories(
    ../boost_1_55_0/_install/lib
)

link_directories(
    ../boost_1_55_0/_install/lib
)
#设置引用的库文件
set(LIBS "")

# #other
set(LIBS ${LIBS} "pthread")

# boost
set(LIBS ${LIBS} "boost_system")

#生成可执行文件
add_executable(webserver ${SRC_SOURCES})

#指定引用的库
target_link_libraries(webserver ${LIBS})

在src目录下创建www目录和build目录,在www目录中新增一个index.html,内容如下:

代码:

代码语言:html
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Boost Http Server</title>
</head>
<body>
    手斯代码八百里
</body>
</html>

然后进入到build目录进行编译

代码语言:shell
复制
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src$ cd build/
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ 
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ 
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ cmake ..
-- The C compiler identification is GNU 11.4.0
-- The CXX compiler identification is GNU 11.4.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /data/project/VSCProject/boost_study/src/build
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ 

执行make -j20编译

编译成功后就会生成一个二进制可执行文件:

代码语言:shell
复制
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ ls -l
总计 492
-rw-rw-r-- 1 zhenghui zhenghui  13847 11月 22 21:15 CMakeCache.txt
drwxrwxr-x 5 zhenghui zhenghui   4096 11月 22 21:16 CMakeFiles
-rw-rw-r-- 1 zhenghui zhenghui   1656 11月 22 21:15 cmake_install.cmake
-rw-rw-r-- 1 zhenghui zhenghui  10982 11月 22 21:15 Makefile
-rwxrwxr-x 1 zhenghui zhenghui 462856 11月 22 21:16 webserver
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ 

运行后会提示如下代码,说明是可以执行的,并且成功了,只不过需要传递过去监听的IP,端口和网站根目录:

代码语言:shell
复制
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ ./webserver 
Usage: http_server <address> <port> <doc_root>
  For IPv4, try:
    receiver 0.0.0.0 80 .
  For IPv6, try:
    receiver 0::0 80 .
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ 

运行测试

可以看到,如果自己运行时没有权限的话,可以使用sudo

代码语言:shell
复制
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ 
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ ./webserver 0.0.0.0 80 ../www/
exception: bind: Permission denied
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ sudo ./webserver 0.0.0.0 80 ../www/
[sudo] zhenghui 的密码: 
(base) zhenghui@zh-pc:/data/project/VSCProject/boost_study/src/build$ 

浏览器访问:http://127.0.0.1:80

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 站在巨人的肩膀上
    • boost库开发环境搭建下载&编译
    • 学习boost库
      • 1、访问boost库的文档(含API)
        • 2、如何找到boost的http例子
        • 实践boost库
        相关产品与服务
        移动解析 HTTPDNS
        移动解析 HTTPDNS 基于 HTTP 协议向腾讯云的 DNS 服务器发送域名解析请求,替代了基于 DNS 协议向运营商 Local DNS 发起解析请求的传统方式,可以避免 Local DNS 造成的域名劫持和跨网访问问题,解决移动互联网服务中域名解析异常带来的困扰。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档