需要用到的知识点:
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