linux c 实现简易HTTP服务器

需要用到的知识点:

server.c

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <pthread.h>
#include "http.h"

#define BUFFER_SIZE 1024

//处理用户的连接的线程方法
void *handle(void *arg){
    int conn = *((int *)arg),i=0,j=0,len=0;
    char buffer[BUFFER_SIZE];
    char *buf = NULL;
    char temp[1024];
    int fp = -1;
    int count = 0;
    int flag = 0;
    //需要优化
    while(1){
            memset(buffer,0,sizeof(buffer));
            len = recv(conn, buffer, sizeof(buffer),0);
        if (buf == NULL) {
            buf = (char *)malloc(BUFFER_SIZE);
        }else {
            buf = (char *)realloc(buf, (i + 1)*BUFFER_SIZE);
        }
        for (j = 0; j < BUFFER_SIZE; j++) {
            buf[i*BUFFER_SIZE + j] = buffer[j];
            if(buffer[j]==13&&buffer[j+1]==10&&buffer[j+2]==13&&buffer[j+3]==10&&j<BUFFER_SIZE-4){
                flag = 1;
            }
        }
        if(flag)
            break;
        }
    printf("%s\n\n",buf);
    Request res = parseRequest(buf);
    free(buf);
    //处理请求文件  发送数据
    //发送状态码  (用字符串链接)
    len = strlen("HTTP/1.1 200 OK\r\nConnection: close\r\nAccept-Ranges: bytes\r\n")+1;
    buf = (char *)malloc(sizeof(char)*len);
    strcpy(buf,"HTTP/1.1 200 OK\r\nConnection: close\r\nAccept-Ranges: bytes\r\n");
    sprintf(temp,"Content-Type: %s\r\n", getFileType(res.file));
    len += strlen(temp);
    buf = (char *)realloc(buf,sizeof(char)*len);
    strcat(buf,temp);
    printf("filename: %s\n", res.file);
    printf("Content-Length: %d\n", getFileSize(res.file));
    sprintf(temp, "Content-Length: %d\r\n\r\n", getFileSize(res.file));
    len += strlen(temp);
    buf = (char *)realloc(buf,sizeof(char)*len);
    strcat(buf,temp);
    //二进制发送文件
    fp = open(res.file,O_RDONLY);
    while (1) {
        i = read(fp,temp,sizeof
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值