国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼

這篇具有很好參考價值的文章主要介紹了linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

pdf詳情版

01 學習目標

  1. 編寫函數(shù)解析http請求
    ○ GET /hello.html HTTP/1.1\r\n
    ○ 將上述字符串分為三部分解析出來
  2. 編寫函數(shù)根據(jù)文件后綴,返回對應(yīng)的文件類型
  3. sscanf - 讀取格式化的字符串中的數(shù)據(jù)
    ○ 使用正則表達式拆分
    ○ [^ ]的用法
  4. 通過瀏覽器請求目錄數(shù)據(jù)
    ○ 讀指定目錄內(nèi)容
    ? opendir
    ? readdir
    ? closedir
    ○ scandir - 掃描dir目錄下(不包括子目錄)內(nèi)容
  5. http中數(shù)據(jù)特殊字符編碼解碼問題
    ○ 編碼
    ○ 解碼

02 epoll 服務(wù)器epoll模型代碼

epoll_server.c:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#include <ctype.h>
#include "epoll_server.h"

#define MAXSIZE 2000

void epoll_run(int port)
{
    // 創(chuàng)建一個epoll樹的根節(jié)點
    int epfd = epoll_create(MAXSIZE);
    if(epfd == -1)
    {
        perror("epoll_create error");
        exit(1);
    }

    // 添加要監(jiān)聽的節(jié)點
    // 先添加監(jiān)聽lfd
    int lfd = init_listen_fd(port, epfd);

    // 委托內(nèi)核檢測添加到樹上的節(jié)點
    struct epoll_event all[MAXSIZE];
    while(1)
    {
        int ret = epoll_wait(epfd, all, MAXSIZE, -1);
        if(ret == -1)
        {
            perror("epoll_wait error");
            exit(1);
        }

        // 遍歷發(fā)生變化的節(jié)點
        for(int i=0; i<ret; ++i)
        {
            // 只處理讀事件, 其他事件默認不處理
            struct epoll_event *pev = &all[i];
            if(!(pev->events & EPOLLIN))
            {
                // 不是讀事件
                continue;
            }

            if(pev->data.fd == lfd)
            {
                // 接受連接請求
                do_accept(lfd, epfd);
            }
            else
            {
                // 讀數(shù)據(jù)
                do_read(pev->data.fd, epfd);
            }
        }
    }
}


int init_listen_fd(int port, int epfd)
{
    // 創(chuàng)建監(jiān)聽的套接字
    int lfd = socket(AF_INET, SOCK_STREAM, 0);
    if(lfd == -1)
    {
        perror("socket error");
        exit(1);
    }

    // lfd綁定本地IP和port
    struct sockaddr_in serv;
    memset(&serv, 0, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_port = htons(port);
    serv.sin_addr.s_addr = htonl(INADDR_ANY);

    // 端口復(fù)用
    int flag = 1;
    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
    int ret = bind(lfd, (struct sockaddr*)&serv, sizeof(serv));
    if(ret == -1)
    {
        perror("bind error");
        exit(1);
    }

    // 設(shè)置監(jiān)聽
    ret = listen(lfd, 64);
    if(ret == -1)
    {
        perror("listen error");
        exit(1);
    }

    // lfd添加到epoll樹上
    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = lfd;
    ret = epoll_ctl(epfd, EPOLL_CTL_ADD, lfd, &ev);
    if(ret == -1)
    {
        perror("epoll_ctl add lfd error");
        exit(1);
    }

    return lfd;
}

03 epoll模型接受連接請求函數(shù)

// 接受新連接處理
void do_accept(int lfd, int epfd)
{
    struct sockaddr_in client;
    socklen_t len = sizeof(client);
    int cfd = accept(lfd, (struct sockaddr*)&client, &len);
    if(cfd == -1)
    {
        perror("accept error");
        exit(1);
    }

    // 打印客戶端信息
    char ip[64] = {0};
    printf("New Client IP: %s, Port: %d, cfd = %d\n",
           inet_ntop(AF_INET, &client.sin_addr.s_addr, ip, sizeof(ip)),
           ntohs(client.sin_port), cfd);

    // 設(shè)置cfd為非阻塞
    int flag = fcntl(cfd, F_GETFL);
    flag |= O_NONBLOCK;
    fcntl(cfd, F_SETFL, flag);

    // 得到的新節(jié)點掛到epoll樹上
    struct epoll_event ev;
    ev.data.fd = cfd;
    // 邊沿非阻塞模式
    ev.events = EPOLLIN | EPOLLET;
    int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &ev);
    if(ret == -1)
    {
        perror("epoll_ctl add cfd error");
        exit(1);
    }
}

04 getline函數(shù)

linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼,Linux,服務(wù)器,linux,前端

// 解析http請求消息的每一行內(nèi)容
int get_line(int sock, char *buf, int size)
{
    int i = 0;
    char c = '\0';
    int n;
    while ((i < size - 1) && (c != '\n'))
    {
        n = recv(sock, &c, 1, 0);
        if (n > 0)
        {
            if (c == '\r')
            {
                n = recv(sock, &c, 1, MSG_PEEK);
                if ((n > 0) && (c == '\n'))
                {
                    recv(sock, &c, 1, 0);
                }
                else
                {
                    c = '\n';
                }
            }
            buf[i] = c;
            i++;
        }
        else
        {
            c = '\n';
        }
    }
    buf[i] = '\0';

    return i;
}

05 do_read函數(shù)

// 讀數(shù)據(jù)
void do_read(int cfd, int epfd)
{
    // 將瀏覽器發(fā)過來的數(shù)據(jù), 讀到buf中 
    char line[1024] = {0};
    // 讀請求行
    int len = get_line(cfd, line, sizeof(line));
    if(len == 0)
    {
        printf("客戶端斷開了連接...\n");
        // 關(guān)閉套接字, cfd從epoll上del
        disconnect(cfd, epfd);         
    }
    else
    {
        printf("請求行數(shù)據(jù): %s", line);
        printf("============= 請求頭 ============\n");
        // 還有數(shù)據(jù)沒讀完
        // 繼續(xù)讀
        while(len)
        {
            char buf[1024] = {0};
            len = get_line(cfd, buf, sizeof(buf));
            printf("-----: %s", buf);
        }
        printf("============= The End ============\n");
    }

    // 請求行: get /xxx http/1.1
    // 判斷是不是get請求
    if(strncasecmp("get", line, 3) == 0)
    {
        // 處理http請求
        http_request(line, cfd);
        // 關(guān)閉套接字, cfd從epoll上del
        disconnect(cfd, epfd);         
    }
}

06 正則表達式入門

http://deerchao.net/tutorials/regex/regex.htm
http://www.jb51.net/tools/regexsc.htm

正則表達式速查表
linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼,Linux,服務(wù)器,linux,前端
linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼,Linux,服務(wù)器,linux,前端
linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼,Linux,服務(wù)器,linux,前端
linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼,Linux,服務(wù)器,linux,前端
linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼,Linux,服務(wù)器,linux,前端
常用正則表達式
linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼,Linux,服務(wù)器,linux,前端
linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼,Linux,服務(wù)器,linux,前端
linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼,Linux,服務(wù)器,linux,前端
linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼,Linux,服務(wù)器,linux,前端

07 sscanf使用正則表達式格式化字符串

sscanf 函數(shù)
函數(shù)描述: 讀取格式化的字符串中的數(shù)據(jù)。
函數(shù)原型:

int sscanf(
const char *buffer, 
const char *format, [ argument ] ...
);
  1. 取到指定字符為止的字符串。如在下例中,取遇到空格為止字符串。
    1 sscanf(“123456 abcdedf”, “%[^ ]”, buf);
    2 printf(“%s\n”, buf);
    結(jié)果為:123456

  2. 取僅包含指定字符集的字符串。如在下例中,取僅包含1到9和小寫字母的字符串。
    1 sscanf(“123456abcdedfBCDEF”, “%[1-9a-z]”, buf);
    2 printf(“%s\n”, buf);
    結(jié)果為:123456abcdedf

  3. 取到指定字符集為止的字符串。如在下例中,取遇到大寫字母為止的字符串。
    1 sscanf(“123456abcdedfBCDEF”, “%[^A-Z]”, buf);
    2 printf(“%s\n”, buf);
    結(jié)果為:123456abcdedf

08 http_resquest函數(shù)

// 斷開連接的函數(shù)
void disconnect(int cfd, int epfd)
{
    int ret = epoll_ctl(epfd, EPOLL_CTL_DEL, cfd, NULL);
    if(ret == -1)
    {
        perror("epoll_ctl del cfd error");
        exit(1);
    }
    close(cfd);
}

// http請求處理
void http_request(const char* request, int cfd)
{
    // 拆分http請求行
    // get /xxx http/1.1
    char method[12], path[1024], protocol[12];
    sscanf(request, "%[^ ] %[^ ] %[^ ]", method, path, protocol);

    printf("method = %s, path = %s, protocol = %s\n", method, path, protocol);

    // 轉(zhuǎn)碼 將不能識別的中文亂碼 - > 中文
    // 解碼 %23 %34 %5f
    decode_str(path, path);
        // 處理path  /xx
        // 去掉path中的/
        char* file = path+1;
    // 如果沒有指定訪問的資源, 默認顯示資源目錄中的內(nèi)容
    if(strcmp(path, "/") == 0)
    {
        // file的值, 資源目錄的當前位置
        file = "./";
    }

    // 獲取文件屬性
    struct stat st;
    int ret = stat(file, &st);
    if(ret == -1)
    {
        // show 404
        send_respond_head(cfd, 404, "File Not Found", ".html", -1);
        send_file(cfd, "404.html");
    }

    // 判斷是目錄還是文件
    // 如果是目錄
    if(S_ISDIR(st.st_mode))
    {
        // 發(fā)送頭信息
        send_respond_head(cfd, 200, "OK", get_file_type(".html"), -1);
        // 發(fā)送目錄信息
        send_dir(cfd, file);
    }
    else if(S_ISREG(st.st_mode))
    {
        // 文件
        // 發(fā)送消息報頭
        send_respond_head(cfd, 200, "OK", get_file_type(file), st.st_size);
        // 發(fā)送文件內(nèi)容
        send_file(cfd, file);
    }
}

09 發(fā)送http響應(yīng)頭函數(shù)

// 發(fā)送響應(yīng)頭
void send_respond_head(int cfd, int no, const char* desp, const char* type, long len)
{
    char buf[1024] = {0};
    // 狀態(tài)行
    sprintf(buf, "http/1.1 %d %s\r\n", no, desp);
    send(cfd, buf, strlen(buf), 0);
    // 消息報頭
    sprintf(buf, "Content-Type:%s\r\n", type);
    sprintf(buf+strlen(buf), "Content-Length:%ld\r\n", len);
    send(cfd, buf, strlen(buf), 0);
    // 空行
    send(cfd, "\r\n", 2, 0);
}

10 發(fā)送普通文件函數(shù)實現(xiàn)

// 發(fā)送文件
void send_file(int cfd, const char* filename)
{
    // 打開文件
    int fd = open(filename, O_RDONLY);
    if(fd == -1)
    {
        // show 404
        return;
    }

    // 循環(huán)讀文件
    char buf[4096] = {0};
    int len = 0;
    while( (len = read(fd, buf, sizeof(buf))) > 0 )
    {
        // 發(fā)送讀出的數(shù)據(jù)
        send(cfd, buf, len, 0);
    }
    if(len == -1)
    {
        perror("read file error");
        exit(1);
    }

    close(fd);
}

11 使用readdir讀目錄和scandir讀目錄

#include <dirent.h>
int scandir(const char *dirp,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **,
const struct dirent **));

dirp
-當前要掃描的目錄
namelist
-struct dirent** ptr;
-struct dirent* ptr[];
-&ptr;

filter
-NULL

compar
○ 文件名顯示的時候, 指定排序規(guī)則
? alphasort
? versionsort

// 發(fā)送目錄內(nèi)容
void send_dir(int cfd, const char* dirname)
{
    // 拼一個html頁面<table></table>
    char buf[4094] = {0};

    sprintf(buf, "<html><head><title>目錄名: %s</title></head>", dirname);
    sprintf(buf+strlen(buf), "<body><h1>當前目錄: %s</h1><table>", dirname);

    char enstr[1024] = {0};
    char path[1024] = {0};
    // 目錄項二級指針
    struct dirent** ptr;
    int num = scandir(dirname, &ptr, NULL, alphasort);
    // 遍歷
    for(int i=0; i<num; ++i)
    {
        char* name = ptr[i]->d_name;

        // 拼接文件的完整路徑
        sprintf(path, "%s/%s", dirname, name);
        printf("path = %s ===================\n", path);
        struct stat st;
        stat(path, &st);

        encode_str(enstr, sizeof(enstr), name);
        // 如果是文件
        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);
        }
        send(cfd, buf, strlen(buf), 0);
        memset(buf, 0, sizeof(buf));
        // 字符串拼接
    }

    sprintf(buf+strlen(buf), "</table></body></html>");
    send(cfd, buf, strlen(buf), 0);

    printf("dir message send OK!!!!\n");
#if 0
    // 打開目錄
    DIR* dir = opendir(dirname);
    if(dir == NULL)
    {
        perror("opendir error");
        exit(1);
    }

    // 讀目錄
    struct dirent* ptr = NULL;
    while( (ptr = readdir(dir)) != NULL )
    {
        char* name = ptr->d_name;
    }
    closedir(dir);
#endif
}

12 處理http協(xié)議需要編碼和解碼的原因

url在數(shù)據(jù)傳輸過程中不支持中文,需要轉(zhuǎn)碼。

  • 漢字
  • 特殊字符
    ○ 查看manpage
    ? man ascii
    ○ 要處理可見字符
    ? 從space開始 - 32
    ? 前0-31個不可見
    ○ 不需要轉(zhuǎn)換的特殊字符
    ? .
    ? _
    ? *
    ? /
    ? ~
    ? 0-9
    ? a-z
    ? A-Z
    ○ 需要轉(zhuǎn)換的字符使用其16進制的值前加%表示

可以在shell下通過unicode工具查看
安裝unicode
sudo apt-get install unicode

13 編解碼函數(shù)介紹

/*
 *  這里的內(nèi)容是處理%20之類的東西!是"解碼"過程。
 *  %20 URL編碼中的‘ ’(space)
 *  %21 '!' %22 '"' %23 '#' %24 '$'
 *  %25 '%' %26 '&' %27 ''' %28 '('......
 *  相關(guān)知識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';
}

14 程序測試

epoll_server.h:

#ifndef _EPOLL_SERVER_H
#define _EPOLL_SERVER_H

int init_listen_fd(int port, int epfd);
void epoll_run(int port);
void do_accept(int lfd, int epfd);
void do_read(int cfd, int epfd);
int get_line(int sock, char *buf, int size);
void disconnect(int cfd, int epfd);
void http_request(const char* request, int cfd);
void send_respond_head(int cfd, int no, const char* desp, const char* type, long len);
void send_file(int cfd, const char* filename);
void send_dir(int cfd, const char* dirname);
void encode_str(char* to, int tosize, const char* from);
void decode_str(char *to, char *from);
const char *get_file_type(const char *name);

#endif

epoll_server.c:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#include <ctype.h>
#include "epoll_server.h"

#define MAXSIZE 2000

void epoll_run(int port)
{
    // 創(chuàng)建一個epoll樹的根節(jié)點
    int epfd = epoll_create(MAXSIZE);
    if(epfd == -1)
    {
        perror("epoll_create error");
        exit(1);
    }

    // 添加要監(jiān)聽的節(jié)點
    // 先添加監(jiān)聽lfd
    int lfd = init_listen_fd(port, epfd);

    // 委托內(nèi)核檢測添加到樹上的節(jié)點
    struct epoll_event all[MAXSIZE];
    while(1)
    {
        int ret = epoll_wait(epfd, all, MAXSIZE, -1);
        if(ret == -1)
        {
            perror("epoll_wait error");
            exit(1);
        }

        // 遍歷發(fā)生變化的節(jié)點
        for(int i=0; i<ret; ++i)
        {
            // 只處理讀事件, 其他事件默認不處理
            struct epoll_event *pev = &all[i];
            if(!(pev->events & EPOLLIN))
            {
                // 不是讀事件
                continue;
            }

            if(pev->data.fd == lfd)
            {
                // 接受連接請求
                do_accept(lfd, epfd);
            }
            else
            {
                // 讀數(shù)據(jù)
                do_read(pev->data.fd, epfd);
            }
        }
    }
}

// 讀數(shù)據(jù)
void do_read(int cfd, int epfd)
{
    // 將瀏覽器發(fā)過來的數(shù)據(jù), 讀到buf中 
    char line[1024] = {0};
    // 讀請求行
    int len = get_line(cfd, line, sizeof(line));
    if(len == 0)
    {
        printf("客戶端斷開了連接...\n");
        // 關(guān)閉套接字, cfd從epoll上del
        disconnect(cfd, epfd);         
    }
    else
    {
        printf("請求行數(shù)據(jù): %s", line);
        printf("============= 請求頭 ============\n");
        // 還有數(shù)據(jù)沒讀完
        // 繼續(xù)讀
        while(len)
        {
            char buf[1024] = {0};
            len = get_line(cfd, buf, sizeof(buf));
            printf("-----: %s", buf);
        }
        printf("============= The End ============\n");
    }

    // 請求行: get /xxx http/1.1
    // 判斷是不是get請求
    if(strncasecmp("get", line, 3) == 0)
    {
        // 處理http請求
        http_request(line, cfd);
        // 關(guān)閉套接字, cfd從epoll上del
        disconnect(cfd, epfd);         
    }
}

// 斷開連接的函數(shù)
void disconnect(int cfd, int epfd)
{
    int ret = epoll_ctl(epfd, EPOLL_CTL_DEL, cfd, NULL);
    if(ret == -1)
    {
        perror("epoll_ctl del cfd error");
        exit(1);
    }
    close(cfd);
}

// http請求處理
void http_request(const char* request, int cfd)
{
    // 拆分http請求行
    // get /xxx http/1.1
    char method[12], path[1024], protocol[12];
    sscanf(request, "%[^ ] %[^ ] %[^ ]", method, path, protocol);

    printf("method = %s, path = %s, protocol = %s\n", method, path, protocol);

    // 轉(zhuǎn)碼 將不能識別的中文亂碼 - > 中文
    // 解碼 %23 %34 %5f
    decode_str(path, path);
        // 處理path  /xx
        // 去掉path中的/
        char* file = path+1;
    // 如果沒有指定訪問的資源, 默認顯示資源目錄中的內(nèi)容
    if(strcmp(path, "/") == 0)
    {
        // file的值, 資源目錄的當前位置
        file = "./";
    }

    // 獲取文件屬性
    struct stat st;
    int ret = stat(file, &st);
    if(ret == -1)
    {
        // show 404
        send_respond_head(cfd, 404, "File Not Found", ".html", -1);
        send_file(cfd, "404.html");
    }

    // 判斷是目錄還是文件
    // 如果是目錄
    if(S_ISDIR(st.st_mode))
    {
        // 發(fā)送頭信息
        send_respond_head(cfd, 200, "OK", get_file_type(".html"), -1);
        // 發(fā)送目錄信息
        send_dir(cfd, file);
    }
    else if(S_ISREG(st.st_mode))
    {
        // 文件
        // 發(fā)送消息報頭
        send_respond_head(cfd, 200, "OK", get_file_type(file), st.st_size);
        // 發(fā)送文件內(nèi)容
        send_file(cfd, file);
    }
}

// 發(fā)送目錄內(nèi)容
void send_dir(int cfd, const char* dirname)
{
    // 拼一個html頁面<table></table>
    char buf[4094] = {0};

    sprintf(buf, "<html><head><title>目錄名: %s</title></head>", dirname);
    sprintf(buf+strlen(buf), "<body><h1>當前目錄: %s</h1><table>", dirname);

    char enstr[1024] = {0};
    char path[1024] = {0};
    // 目錄項二級指針
    struct dirent** ptr;
    int num = scandir(dirname, &ptr, NULL, alphasort);
    // 遍歷
    for(int i=0; i<num; ++i)
    {
        char* name = ptr[i]->d_name;

        // 拼接文件的完整路徑
        sprintf(path, "%s/%s", dirname, name);
        printf("path = %s ===================\n", path);
        struct stat st;
        stat(path, &st);

        encode_str(enstr, sizeof(enstr), name);
        // 如果是文件
        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);
        }
        send(cfd, buf, strlen(buf), 0);
        memset(buf, 0, sizeof(buf));
        // 字符串拼接
    }

    sprintf(buf+strlen(buf), "</table></body></html>");
    send(cfd, buf, strlen(buf), 0);

    printf("dir message send OK!!!!\n");
#if 0
    // 打開目錄
    DIR* dir = opendir(dirname);
    if(dir == NULL)
    {
        perror("opendir error");
        exit(1);
    }

    // 讀目錄
    struct dirent* ptr = NULL;
    while( (ptr = readdir(dir)) != NULL )
    {
        char* name = ptr->d_name;
    }
    closedir(dir);
#endif
}

// 發(fā)送響應(yīng)頭
void send_respond_head(int cfd, int no, const char* desp, const char* type, long len)
{
    char buf[1024] = {0};
    // 狀態(tài)行
    sprintf(buf, "http/1.1 %d %s\r\n", no, desp);
    send(cfd, buf, strlen(buf), 0);
    // 消息報頭
    sprintf(buf, "Content-Type:%s\r\n", type);
    sprintf(buf+strlen(buf), "Content-Length:%ld\r\n", len);
    send(cfd, buf, strlen(buf), 0);
    // 空行
    send(cfd, "\r\n", 2, 0);
}

// 發(fā)送文件
void send_file(int cfd, const char* filename)
{
    // 打開文件
    int fd = open(filename, O_RDONLY);
    if(fd == -1)
    {
        // show 404
        return;
    }

    // 循環(huán)讀文件
    char buf[4096] = {0};
    int len = 0;
    while( (len = read(fd, buf, sizeof(buf))) > 0 )
    {
        // 發(fā)送讀出的數(shù)據(jù)
        send(cfd, buf, len, 0);
    }
    if(len == -1)
    {
        perror("read file error");
        exit(1);
    }

    close(fd);
}

// 解析http請求消息的每一行內(nèi)容
int get_line(int sock, char *buf, int size)
{
    int i = 0;
    char c = '\0';
    int n;
    while ((i < size - 1) && (c != '\n'))
    {
        n = recv(sock, &c, 1, 0);
        if (n > 0)
        {
            if (c == '\r')
            {
                n = recv(sock, &c, 1, MSG_PEEK);
                if ((n > 0) && (c == '\n'))
                {
                    recv(sock, &c, 1, 0);
                }
                else
                {
                    c = '\n';
                }
            }
            buf[i] = c;
            i++;
        }
        else
        {
            c = '\n';
        }
    }
    buf[i] = '\0';

    return i;
}

// 接受新連接處理
void do_accept(int lfd, int epfd)
{
    struct sockaddr_in client;
    socklen_t len = sizeof(client);
    int cfd = accept(lfd, (struct sockaddr*)&client, &len);
    if(cfd == -1)
    {
        perror("accept error");
        exit(1);
    }

    // 打印客戶端信息
    char ip[64] = {0};
    printf("New Client IP: %s, Port: %d, cfd = %d\n",
           inet_ntop(AF_INET, &client.sin_addr.s_addr, ip, sizeof(ip)),
           ntohs(client.sin_port), cfd);

    // 設(shè)置cfd為非阻塞
    int flag = fcntl(cfd, F_GETFL);
    flag |= O_NONBLOCK;
    fcntl(cfd, F_SETFL, flag);

    // 得到的新節(jié)點掛到epoll樹上
    struct epoll_event ev;
    ev.data.fd = cfd;
    // 邊沿非阻塞模式
    ev.events = EPOLLIN | EPOLLET;
    int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &ev);
    if(ret == -1)
    {
        perror("epoll_ctl add cfd error");
        exit(1);
    }
}

int init_listen_fd(int port, int epfd)
{
    // 創(chuàng)建監(jiān)聽的套接字
    int lfd = socket(AF_INET, SOCK_STREAM, 0);
    if(lfd == -1)
    {
        perror("socket error");
        exit(1);
    }

    // lfd綁定本地IP和port
    struct sockaddr_in serv;
    memset(&serv, 0, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_port = htons(port);
    serv.sin_addr.s_addr = htonl(INADDR_ANY);

    // 端口復(fù)用
    int flag = 1;
    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
    int ret = bind(lfd, (struct sockaddr*)&serv, sizeof(serv));
    if(ret == -1)
    {
        perror("bind error");
        exit(1);
    }

    // 設(shè)置監(jiān)聽
    ret = listen(lfd, 64);
    if(ret == -1)
    {
        perror("listen error");
        exit(1);
    }

    // lfd添加到epoll樹上
    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = lfd;
    ret = epoll_ctl(epfd, EPOLL_CTL_ADD, lfd, &ev);
    if(ret == -1)
    {
        perror("epoll_ctl add lfd error");
        exit(1);
    }

    return lfd;
}

// 16進制數(shù)轉(zhuǎn)化為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;
}

/*
 *  這里的內(nèi)容是處理%20之類的東西!是"解碼"過程。
 *  %20 URL編碼中的‘ ’(space)
 *  %21 '!' %22 '"' %23 '#' %24 '$'
 *  %25 '%' %26 '&' %27 ''' %28 '('......
 *  相關(guān)知識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';

}

// 通過文件名獲取文件的類型
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";
}

main.c:文章來源地址http://www.zghlxwxcb.cn/news/detail-601961.html

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "epoll_server.h"

int main(int argc, const char* argv[])
{
    if(argc < 3)
    {
        printf("eg: ./a.out port path\n");
        exit(1);
    }

    // 端口
    int port = atoi(argv[1]);
    // 修改進程的工作目錄, 方便后續(xù)操作
    int ret = chdir(argv[2]);
    if(ret == -1)
    {
        perror("chdir error");
        exit(1);
    }
    
    // 啟動epoll模型 
    epoll_run(port);

    return 0;
}

到了這里,關(guān)于linux高并發(fā)web服務(wù)器開發(fā)(web服務(wù)器)18_函數(shù)解析http請求, 正則表達式,sscanf使用,http中數(shù)據(jù)特殊字符編碼解碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包