Browse Source

提交httpserver demo

master
adminPyf 3 years ago
parent
commit
0532755817
5 changed files with 363 additions and 0 deletions
  1. +2
    -0
      test_http_server/Makefile
  2. BIN
      test_http_server/app.ico
  3. +167
    -0
      test_http_server/first_libevent.vcxproj
  4. +17
    -0
      test_http_server/index.html
  5. +177
    -0
      test_http_server/test_http_server.cpp

+ 2
- 0
test_http_server/Makefile View File

@ -0,0 +1,2 @@
test_http_server: test_http_server.cpp
g++ $^ -o $@ -levent

BIN
test_http_server/app.ico View File

Before After

+ 167
- 0
test_http_server/first_libevent.vcxproj View File

@ -0,0 +1,167 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{129BF326-BFEE-4F1C-920C-0C302BB84895}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>firstlibevent</RootNamespace>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
<ProjectName>test_http_server</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\..\include</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>..\..\lib</AdditionalLibraryDirectories>
<AdditionalDependencies>libevent.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="test_http_server.cpp" />
</ItemGroup>
<ItemGroup>
<None Include="index.html">
<DeploymentContent>true</DeploymentContent>
</None>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

+ 17
- 0
test_http_server/index.html View File

@ -0,0 +1,17 @@
<HTML>
<HEAD>
<meta charset="utf8" />
<TITLE>test http server</TITLE>
</HEAD>
<BODY>
<h1>test http server</h1>
111112222
<img src="app.ico" />
<form method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</BODY>
</HTML>

+ 177
- 0
test_http_server/test_http_server.cpp View File

@ -0,0 +1,177 @@

#include <iostream>
#include <event2/http.h>
#include<event2/event.h>
#include <event2/listener.h>
#include <event2/keyvalq_struct.h>
#include <event2/buffer.h>
#include <string.h>
#ifndef _WIN32
#include <signal.h>
#include "test_http_server.h"
#endif // !_WIN32
using namespace std;
#define WEBROOT "."
#define DEFAULTINDEX "index.html"
void http_cb(struct evhttp_request* request, void *arg) {
cout << "http_cb" << endl;
//1 获取浏览器请求信息
//url
const char* uri = evhttp_request_get_uri(request);
cout << "uri:" << uri << endl;
//获取请求类型Get Post
string cmdtype;
evhttp_cmd_type type = evhttp_request_get_command(request);
switch (type)
{
case EVHTTP_REQ_GET:
cout << "EVHTTP_REQ_GET" << endl;
break;
case EVHTTP_REQ_POST:
break;
case EVHTTP_REQ_HEAD:
break;
case EVHTTP_REQ_PUT:
break;
case EVHTTP_REQ_DELETE:
break;
case EVHTTP_REQ_OPTIONS:
break;
case EVHTTP_REQ_TRACE:
break;
case EVHTTP_REQ_CONNECT:
break;
case EVHTTP_REQ_PATCH:
break;
default:
break;
}
//消息报头
evkeyvalq *headers = evhttp_request_get_input_headers(request);
cout << "========headers========\n" << endl;
for (evkeyval *p = headers->tqh_first; p != NULL; p = p->next.tqe_next) {
cout << p->key << ":" << p->value << endl;
}
//请求正文
evbuffer*inbuf = evhttp_request_get_input_buffer(request);
char buf[1024] = { 0 };
cout << "=========Input data ===========" << endl;
while (evbuffer_get_length(inbuf)) {
int n = evbuffer_remove(inbuf, buf, sizeof(buf) - 1);
if (n > 0) {
buf[n] = '\0';
cout << buf << endl;
}
}
//2 回复浏览器
//状态行 响应正文
//消息报头
evkeyvalq *outhead = evhttp_request_get_output_headers(request);
//分析URI
//设置根目录
string filepath = WEBROOT;
filepath += uri;
if (strcmp(uri, "/") == 0) {
filepath += DEFAULTINDEX;
}
//文件后缀
int pos = filepath.rfind(".");
string postfix = filepath.substr(pos+1,filepath.size() - (pos+1));
if (postfix == "jpg" || postfix == "png" || postfix == "gif" || postfix == "ico") {
string temp = "image/" + postfix;
evhttp_add_header(outhead, "Content-Type", temp.c_str());
}
else if (postfix == "zip") {
evhttp_add_header(outhead, "Content-Type", "application/zip");
}
else if (postfix == "html") {
evhttp_add_header(outhead, "Content-Type", "text/html;charset=UTF8");
}
else if (postfix == "css") {
evhttp_add_header(outhead, "Content-Type", "text/css");
}
FILE *fp = fopen(filepath.c_str(), "rb");
if (!fp) {
evhttp_send_reply(request, HTTP_NOTFOUND, "", 0);
return;
}
evbuffer *outbuf = evhttp_request_get_output_buffer(request);
for (;;) {
int len = fread(buf, 1,sizeof(buf), fp);
if (len <= 0)
break;
evbuffer_add(outbuf, buf, len);
}
fclose(fp);
evhttp_send_reply(request, HTTP_OK, "", outbuf);
}
int main()
{
#ifdef _WIN32
//初始化socket库
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
#else
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { //忽略管道信号,发送数据给已关闭的socket,会飞掉!
return 1;
}
#endif
//创建libevent上下文
event_base* base = event_base_new();
if (base) {
std::cout << "test server" << "\n";
}
//http 服务器
//1.创建evhttp上下文
evhttp *evh = evhttp_new(base);
//2.绑定端口、IP
if (evhttp_bind_socket(evh, "0.0.0.0", 8080) != 0) {
cout << "绑定失败" << endl;
}
//3. 设定回调函数
evhttp_set_gencb(evh, http_cb, 0);
if (base)
event_base_dispatch(base); //事件分发处理
if (base)
event_base_free(base);
if (evh)
evhttp_free(evh);
#if _WIN32
WSACleanup();
#endif // _WIN32
return 0;
}

Loading…
Cancel
Save