civetweb框架介绍-轻量级的web服务器

服务器


文章目录


前言

CivetWeb基于Mongoose项目,是一个易于使用,功能强大的C / C ++嵌入式Web服务器。
在2013年8月16日, 在编写和分发此项目所依据的原始代码后,Mongoosed的许可证已经更改了。因此,CivetWeb已从上一个MIT版本的Mongoose分叉。自2013年以来,CivetWeb已经看到了各种作者的许多改进。
简而言之,从Mongoose跳转到使用CivetWeb项目,就算因为CivetWeb免费,不需要获取相关的许可证就可以使用。
下载
CivetWeb的GitHub下载地址为:https://github.com/civetweb/civetweb
这里我下载的是master的版本 ,也就是V1.11的最新版本。


civetweb

要搭建自己的个人网站必须得有自己的后台服务程序和前端界面展示程序,因为笔者主要从事c/c++应用程序开发,所有我们后台服务程序选用轻量的c++ civetweb服务框架来做开发,前端初步设想使用AngularJs来实现,后面再说,先来介绍一下我们后台的civetweb

介绍:civetweb是基于Mongoose项目,是一个简单易用,功能强大的c/c++嵌入式web服务器

源码地址:GitHub - civetweb/civetweb: Embedded C/C++ web server

编译:代码下载doc中有编译的说明,比较简单的方式可以使用cmake进行编译[cmake …][make][make install]简单三步即可完成编译

Demo:源码中有简单的Demo程序,小伙伴们可以进入到c++的Demo程序直接进行简单的make编译一下,运行测试一下效果

目标:我们的目标是要在服务器上启动一个civetweb的服务,并能够通过访问网址的时候直接访问到我们的页面,页面我们可以先做一个十分简单的小页面,代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>菜鸟教程(runoob.com)</title>
    </head>
    <body>
        <h1>我的第一个标题</h1>
        <p>我的第一个段落。</p>
    </body>
</html>

这是我从菜鸟教程拿下来的一个示例程序,相信以各位大佬的水平,这种程度的代码完全不需要一个字的解释。

接下来就是我们c++服务器的主程序,其实也是十分的简单,只是对Demo程序略微进行了一点改造就可以达到我们需要的效果了

/* 
 * Copyright (c) 2021-6-5 Super.Yang
 */
 
#include "CivetServer.h"
#include <cstring>
 
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
 
#define DOCUMENT_ROOT "./web_root"
#define PORT "8081"
#define MYWEBPERSONAL_URL "/"
 
class ExampleHandler : public CivetHandler
{
    
    
  public:
	bool handlePost(CivetServer *server, struct mg_connection *conn)
	{
    
    
		return true;
	}
};
 
int main(int argc, char *argv[])
{
    
    
	mg_init_library(0);
	
	const char *options[] = {
    
    "document_root", DOCUMENT_ROOT, "listening_ports", PORT, 0};
    
    std::vector<std::string> cpp_options;
    for (int i = 0; i < (sizeof(options) / sizeof(options[0]) - 1); ++i) {
    
    
        cpp_options.push_back(options[i]);
    }
 
	CivetServer server(cpp_options); // <-- C++ style start
 
	ExampleHandler h_ex;
	server.addHandler(MYWEBPERSONAL_URL, h_ex);
 
	while (1) {
    
    
		sleep(1);
	}
 
	mg_exit_library();
 
	return 0;
}

程序最主要的地方就是document_root的设置可以选择一个我们任何比较合适放置我们页面文件的目录即可

运行

1.配置civetweb的运行参数:

document_root:表示civetweb读取的路径的,该参数应设置位对应的网页路径;

listening_ports:表示civetweb监听的端口号,若为8080s,则表示使用https协议监听8080端口;

ssl_certificate:设置server.pem的路径,e.g: /usr/local/bin/server.pem

2.运行civetweb: ./civetweb

3.使用浏览器访问对应的网站:

若使用http协议,则网站地址为 http://目标IP:目标端口
若使用https协议,则网站地址为https://目标IP:目标端口

这样程序部署到我们的服务器直接运行起来之后从公网只要访问ip:port/index.html就可以看到我们菜鸟教程示例的页面了。

猜你喜欢

转载自blog.csdn.net/zyq880625/article/details/131195483