资源简介
linux用c语言写的微型web服务器,简介或教程看这里:blog.csdn.net/sumkee911/article/details/50351862
代码片段和文件信息
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include “threadpool/threadpool.h“
// 服务器配置
#define PORT 80
#define MAX_LISTEN 128
#define MAX_EPOLL MAX_LISTEN+1
#define THREAD_COUNT 10
#define DEFAULT_PAGE “index.html“
#define SEND_BUF 2048
#define RECV_BUF 2048
#define SERVE_STATIC 0 // 处理静态请求
#define SERVE_DYNAMIC 1 // 处理动态请求
// 服务器根目录
static char g_root[256]=““;
// 线程池
static ThreadPool g_pool;
// 多路复用io接口(epoll)
static int g_epoll_fd;
static void del_from_epoll(int efd int fd);
void get_file_type(char *type char *filepath) {
if(strstr(filepath“.html“)) strcpy(type “text/html“);
else if(strstr(filepath “.gif“)) strcpy(type “image/gif“);
else if(strstr(filepath “.jpg“)) strcpy(type “image/jpeg“);
else if(strstr(filepath “.png“)) strcpy(type “image/png“);
else if(strstr(filepath “.css“)) strcpy(type “text/css“);
else if(strstr(filepath “.js“)) strcpy(type “application/x-javascript“);
else strcpy(type “text/plain“);
}
void get_absolute_path(char *abfilepath char *rt char *filepath) {
sprintf(abfilepath “%s%s“ rt filepath);
}
void serve_error(int fd char *filepathconst char *errnum
const char *shortmsg const char *longmsg) {
char head[SEND_BUF] body[SEND_BUF];
memset(body 0 sizeof(body));
memset(head 0 sizeof(head));
// 网页错误页面
sprintf(body “tle>Tiny Web Server Error tle>“);
sprintf(body “%sTiny Web Server Error
“ body);
sprintf(body “%sError code: %s
“body errnum);
sprintf(body “%sCause: %s %s
“ bodylongmsg filepath);
// http 头
sprintf(head “HTTP/1.1 %s %s\r\n“ errnum shortmsg);
sprintf(head “%sContent-type: text/html\r\n“ head);
sprintf(head “%sContent-length: %d\r\n\r\n“ head(int)strlen(body));
// 发送
send(fd head strlen(head) MSG_NOSIGNAL);
send(fd body strlen(body) MSG_NOSIGNAL);
}
void serve_static(int fd char *filepath long filesize) {
int filefd;
char buf[SEND_BUF] filetype[128]*filemap;
memset(filetype 0 sizeof(filetype));
memset(buf 0 sizeof(buf));
// 发送http头
get_file_type(filetype filepath); // 获取文件类型
sprintf(buf “HTTP/1.1 200 OK\r\n“);
sprintf(buf “%sServer: Tiny Web Server\r\n“ buf);
sprintf(buf “%sContent-length: %ld\r\n“buf filesize);
sprintf(buf “%sContent-type: %s\r\n\r\n“ buf filetype);
send(fd buf strlen(buf) MSG_NOSIGNAL);
// 发送文件内容
filefd = open(filepath O_RDONLY);
filemap = (char *)mmap(0 filesize PROT_READ MAP_PRIVATE filefd 0);
close(filefd);
send(fd filemap filesize MSG_NOSIGNAL);
m
评论
共有 条评论