資源簡介
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
評論
共有 條評論