Linux 用libevent实现的简单http服务器

main.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include "libev.h"
#include <string.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h> int main(int argc, char** argv){ // 端口
int port = atoi(argv[1]);
// 修改进程的工作目录, 方便后续操作
int ret = chdir(argv[2]);
if(ret == -1){
perror("chdir error");
exit(1);
} struct event_base* base = NULL;
base = event_base_new();
if(base == NULL){
perror("event_base_new");
exit(1);
} struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY); struct evconnlistener* lis =
evconnlistener_new_bind(base, listencb, base, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1, (struct sockaddr*)&addr, sizeof(addr)); if(!lis){
perror("evconnlistener_new_bind");
exit(1);
} event_base_dispatch(base);
event_base_free(base);
}

libev.h

#ifndef __LIBEV__
#define __LIBEV__ #include <event2/bufferevent.h>
#include <event2/listener.h> void listencb(struct evconnlistener* listener, evutil_socket_t fd,
struct sockaddr* cli, int len, void* ptr);
void readcb (struct bufferevent* bev,void* ctx);
void writecb (struct bufferevent* bev,void* ctx);
void eventcb (struct bufferevent* bev,short what,void* ctx);
#endif

libev.c

#include "libev.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "libev.h"
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h> // 通过文件名获取文件的类型
const char *get_file_type(const char *name){
char* dot; // 自右向左查找‘.’字符, 如不存在返回NULL
dot = strrchr(name, '.');
if (dot == NULL)
return "text/plain; charset=utf-8";
if (strcmp(dot, ".html") == 0 || strcmp(dot, ".htm") == 0)
return "text/html; charset=utf-8";
if (strcmp(dot, ".jpg") == 0 || strcmp(dot, ".jpeg") == 0)
return "image/jpeg";
if (strcmp(dot, ".gif") == 0)
return "image/gif";
if (strcmp(dot, ".png") == 0)
return "image/png";
if (strcmp(dot, ".css") == 0)
return "text/css";
if (strcmp(dot, ".au") == 0)
return "audio/basic";
if (strcmp( dot, ".wav" ) == 0)
return "audio/wav";
if (strcmp(dot, ".avi") == 0)
return "video/x-msvideo";
if (strcmp(dot, ".mov") == 0 || strcmp(dot, ".qt") == 0)
return "video/quicktime";
if (strcmp(dot, ".mpeg") == 0 || strcmp(dot, ".mpe") == 0)
return "video/mpeg";
if (strcmp(dot, ".vrml") == 0 || strcmp(dot, ".wrl") == 0)
return "model/vrml";
if (strcmp(dot, ".midi") == 0 || strcmp(dot, ".mid") == 0)
return "audio/midi";
if (strcmp(dot, ".mp3") == 0)
return "audio/mpeg";
if (strcmp(dot, ".ogg") == 0)
return "application/ogg";
if (strcmp(dot, ".pac") == 0)
return "application/x-ns-proxy-autoconfig"; return "text/plain; charset=utf-8";
}
// 16进制数转化为10进制
int hexit(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10; return 0;
} /*
* 这里的内容是处理%20之类的东西!是"解码"过程。
* %20 URL编码中的‘ ’(space)
* %21 '!' %22 '"' %23 '#' %24 '$'
* %25 '%' %26 '&' %27 ''' %28 '('......
* 相关知识html中的‘ ’(space)是&nbsp
*/
void encode_str(char* to, int tosize, const char* from)
{
int tolen; for (tolen = 0; *from != '\0' && tolen + 4 < tosize; ++from)
{
if (isalnum(*from) || strchr("/_.-~", *from) != (char*)0)
{
*to = *from;
++to;
++tolen;
}
else
{
sprintf(to, "%%%02x", (int) *from & 0xff);
to += 3;
tolen += 3;
} }
*to = '\0';
} void decode_str(char *to, char *from)
{
for ( ; *from != '\0'; ++to, ++from )
{
if (from[0] == '%' && isxdigit(from[1]) && isxdigit(from[2]))
{ *to = hexit(from[1])*16 + hexit(from[2]); from += 2;
}
else
{
*to = *from; } }
*to = '\0'; } void listencb(struct evconnlistener* listener, evutil_socket_t fd,
struct sockaddr* cli, int len, void* ptr){
struct event_base* base = ptr;
struct bufferevent* bev =
bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); //set callback
bufferevent_setcb(bev, readcb, writecb, eventcb, NULL);
bufferevent_enable(bev, EV_READ | EV_WRITE); } // 断开连接的函数
void disconnect(struct bufferevent* bev){
bufferevent_disable(bev, EV_READ | EV_WRITE);
} void send_respond_head(struct bufferevent* bev, int no, const char* desp, const char* type, long len){
char buf[1024] = {0};
// 状态行
sprintf(buf, "http/1.1 %d %s\r\n", no, desp);
bufferevent_write(bev, buf, strlen(buf));
// 消息报头
memset(buf, 0, sizeof buf);
sprintf(buf, "Content-Type:%s\r\n", type);
sprintf(buf+strlen(buf), "Content-Length:%ld\r\n", len);
bufferevent_write(bev, buf, strlen(buf));
// 空行
bufferevent_write(bev, "\r\n", 2);
} void send_file(struct bufferevent* bev, const char* path){
int fd = open(path, O_RDONLY);
if(fd == -1){
//todo 404
perror("open err");
exit(1);
} char buf[4096];
int ret = 0;
while((ret = read(fd, buf, sizeof buf)) > 0){
bufferevent_write(bev, buf, ret);
}
if(ret == -1){
perror("read err");
exit(1);
}
close(fd);
} void send_dir(struct bufferevent* bev, const char* path){
char file[1024] = {0};
char buf[4096] = {0};
sprintf(buf, "<html><head><title>目录名: %s</title></head>", path);
sprintf(buf+strlen(buf), "<body><h1>当前目录: %s</h1><table>", path);
#if 1
DIR* dir = opendir(path);
if(dir == NULL){
perror("opendir error");
exit(1);
}
// 读目录
char enstr[1024] = {0};
struct dirent* ptr = NULL;
while((ptr = readdir(dir)) != NULL){
char* name = ptr->d_name;
// 拼接文件的完整路径
sprintf(file, "%s/%s", path, name); encode_str(enstr, sizeof(enstr), name);
struct stat st;
int ret = stat(file, &st);
if(ret == -1){
perror("stat err");
exit(1);
}
// 如果是文件
if(S_ISREG(st.st_mode)){
sprintf(buf+strlen(buf),
"<tr><td><a href=\"%s\">%s</a></td><td>%ld</td></tr>",
enstr, name, (long)st.st_size);
}
// 如果是目录
else if(S_ISDIR(st.st_mode)){
sprintf(buf+strlen(buf),
"<tr><td><a href=\"%s/\">%s/</a></td><td>%ld</td></tr>",
enstr, name, (long)st.st_size);
}
bufferevent_write(bev, buf, strlen(buf));
memset(buf, 0, sizeof(buf));
}
sprintf(buf+strlen(buf), "</table></body></html>");
bufferevent_write(bev, buf, strlen(buf));
closedir(dir);
#endif
} void http_get_request(const char* line, struct bufferevent* bev){
char method[12] = {0};
char res[1024] = {0};
sscanf(line, "%[^ ] %[^ ]", method, res); // 转码 将不能识别的中文乱码 - > 中文
// 解码 %23 %34 %5f
char destr[1024];
decode_str(destr, res);
// 处理path /xx
// 去掉path中的/
char* file = destr + 1;
char fbuf[1024];
if(strcmp(res, "/") == 0){
file = "./";
//getcwd(fbuf, sizeof(fbuf));
//printf("root:[%s]\n", fbuf);
// file = fbuf;
} struct stat st;
printf("file:[%s]\n", file);
int ret = stat(file, &st);
if(ret == -1){
//todo 404
perror("stat error");
exit(1);
}
if(S_ISDIR(st.st_mode)){
//dir
// 发送头信息
send_respond_head(bev, 200, "OK", get_file_type(".html"), 100000);
send_dir(bev, file);
}
else if(S_ISREG(st.st_mode)){
//reg file
send_respond_head(bev, 200, "OK", get_file_type(file), st.st_size);
send_file(bev, file);
}
} void readcb (struct bufferevent* bev,void* ctx){
struct evbuffer* evbuf = bufferevent_get_input(bev); char* line;
size_t len;
line = evbuffer_readln(evbuf, &len, EVBUFFER_EOL_CRLF);
/*
char* tmp = line;
while(1){
tmp = evbuffer_readln(evbuf, &len, EVBUFFER_EOL_CRLF);
if(tmp) break;
printf("%s\n", tmp);
}
printf("line:[%s]", line);
*/
if(strncasecmp("get", line, 3) == 0){
http_get_request(line, bev);
//disconnect(bev);
} }
void writecb (struct bufferevent* bev,void* ctx){ }
void eventcb (struct bufferevent* bev,short what,void* ctx){ }

c/c++ 学习互助QQ群:877684253

本人微信:xiaoshitou5854

Linux 用libevent实现的简单http服务器的更多相关文章

  1. Linux 用epoll实现的简单http服务器

    Linux 用epoll实现的简单http服务器 main.c #include <stdio.h> #include <sys/types.h> #include <s ...

  2. Linux下Libevent安装和简单实用

    前言 Libevent 是一个用C语言编写的.轻量级的开源高性能事件通知库,主要有以下几个亮点:事件驱动( event-driven),高性能;轻量级,专注于网络,不如 ACE 那么臃肿庞大:源代码相 ...

  3. 转:Linux下使用Nginx搭建简单图片服务器

    最近经常有人问图片上传怎么做,有哪些方案做比较好,也看到过有关于上传图片的做法,但是都不是最好的,今天再这里简单讲一下Nginx实现上传图片以及图片服务器的大致理念. 如果是个人项目或者企业小项目,仅 ...

  4. 【LINUX/UNIX网络编程】之简单多线程服务器(多人群聊系统)

    RT,Linux下使用c实现的多线程服务器.这个真是简单的不能再简单的了,有写的不好的地方,还希望大神轻拍.(>﹏<) 本学期Linux.unix网络编程的第四个作业. 先上实验要求: [ ...

  5. Linux 下 简单客户端服务器通讯模型(TCP)

    原文:Linux 下 简单客户端服务器通讯模型(TCP) 服务器端:server.c #include<stdio.h> #include<stdlib.h> #include ...

  6. 伯克利SocketAPI(一) socket的C语言接口/最简单的服务器和对应的客户端C语言实现

    1. 头文件 2. API函数 3. 最简单的服务器和对应的客户端C语言实现 3.1 server #include <sys/types.h> #include <sys/sock ...

  7. python socket 实现的简单http服务器

    预备知识: 关于http 协议的基础请参考这里. 关于socket 基础函数请参考这里. 关于python 网络编程基础请参考这里. 一.python socket 实现的简单http服务器   废话 ...

  8. Linux网络编程服务器模型选择之并发服务器(上)

    与循环服务器的串行处理不同,并发服务器对服务请求并发处理.循环服务器只能够一个一个的处理客户端的请求,显然效率很低.并发服务器通过建立多个子进程来实现对请求的并发处理.并发服务器的一个难点是如何确定子 ...

  9. csv HTTP简单表服务器

    HTTP Simple Table Server Download Performance testing with JMeter can be done with several JMeter in ...

随机推荐

  1. thinkphp3.2生成二维码

    public function createCode() { Vendor('phpqrcode.phpqrcode'); $object = new \QRcode(); $url = 'http: ...

  2. 安装fiddler后,willow安装

    willow 安装需要与fiddler安装在同一个磁盘,如果出现报错找不到路径,请按下面地址下载willow后重新安装 willow下载地址: https://github.com/QzoneTouc ...

  3. HashMap了解吗?

    HashCode() HashMap 底层实现 HashMap 的长度为什么默认初始长度是16,并且每次resize()的时候,长度必须是2的幂次方? HashMap 死链问题 Java 8 与 Ja ...

  4. Vue生命周期钩子---3

    vue生命周期流程图:4张图 : 生命周期的解析和应用: Vue 实例有一个完整的生命周期,也就是从开始创建.初始化数据.编译模板.挂载Dom→渲染.更新→渲染.卸载等一系列过程,我们称这是 Vue ...

  5. day8_类的装饰器和反射

    """ 类的装饰器: @property 当类的函数属性声明 @property后, 函数属性不需要加括号 即可调用 @staticmethod 当类的函数属性声明 @s ...

  6. markdown 希腊字母

    字母名称 大写 markdown原文 小写 markdown原文alpha A A α \alphabeta B B β \betagamma Γ \Gamma γ \gammadelta Δ \De ...

  7. springboot2 中Druid和ibatis(baomidou) 遇到org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.iflytek.pandaai.service.multi.mapper.TanancyMapper

    调用mapper中任何方法都会出现类似的错误 org.apache.ibatis.binding.BindingException: Invalid bound statement (not foun ...

  8. 【转】pywinauto教程

    一.环境安装 1.命令行安装方法 pip install pywinauto==0.6.7 2.手动安装方法 安装包下载链接:pyWin32: python调用windows api的库https:/ ...

  9. python3爬虫筛选所需要数据

    第一次使用博客园,也是第一篇文章,让我们一起开启学习之旅吧!! 昨天在为某授权系统做安全性测试的时候,可以未授权访问系统的用户登陆统计记录.由此想整理出部分用户名,作为暴力破解的用户名,检查是否存在用 ...

  10. C++:Special Member Functions

    Special Member Functions 区别于定义类的行为的普通成员函数,类内有一类特殊的成员函数,它们负责类的构造.拷贝.移动.销毁. 构造函数 构造函数控制对象的初始化过程,具体来说,就 ...