前言
参考:爱编程的大丙
操作流程图如下:
多线程就是将acceptClient函数和recvHttpRequest函数使用pthread_create函数创建多线程
// 和客户端建立连接
//int acceptClient(int lfd, int epfd);
void* acceptClient(void* arg);
// 接收http请求
//int recvHttpRequest(int cfd, int epfd);
void* recvHttpRequest(void* arg);
main.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "Server.h"
// usage:
// bin port resourcepath
int main(int argc ,char * argv[]){
if (argc < 3)
{
printf("usage:./a.out port path\n");
return -1;
}
unsigned short port = atoi(argv[1]);
// 切换服务器的工作路径
chdir(argv[2]);
// 初始化用于监听的套接字
int lfd = initListenFd(port);
// 启动服务器程序
epollRun(lfd);
return 0;
}
server.c
#include "Server.h"
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <strings.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <sys/sendfile.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <ctype.h>
// 初始化监听的套接字
int initListenFd(unsigned short port)
{
// 1. 创建监听的fd
int lfd = socket(AF_INET, SOCK_STREAM, 0);
if (lfd == -1)
{
perror("socket");
return -1;
}
// 2. 设置端口复用
int opt = 1;
int ret = setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt);
if (ret == -1)
{
perror("setsockopt");
return -1;
}
// 3. 绑定
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY; //定义:表示绑定所有可用网络接口的IP地址(即0.0.0.0)
ret = bind(lfd, (struct sockaddr*)&addr, sizeof addr);
if (ret == -1)
{
perror("bind");
return -1;
}
// 4. 设置监听
ret = listen(lfd, 128);
if (ret == -1)
{
perror("listen");
return -1;
}
// 返回fd
return lfd;
}
int epollRun(int lfd)
{
// 1. 创建epoll实例
int epfd = epoll_create(1);
if (epfd == -1)
{
perror("epoll_create");
return -1;
}
// 2. lfd 上树
struct epoll_event ev;
ev.data.fd = lfd;
ev.events = EPOLLIN;
int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, lfd, &ev);
if (ret == -1)
{
perror("epoll_ctl");
return -1;
}
// 3. 检测
struct epoll_event evs[1024];
int size = sizeof(evs) / sizeof(struct epoll_event);
while (1)
{
int num = epoll_wait(epfd, evs, size, -1);
for (int i = 0; i < num; ++i)
{
int fd = evs[i].data.fd;
if (fd == lfd)//监听套接字
{
// 建立新连接 accept
acceptClient(lfd, epfd);
}
else
{
// 主要是接收对端的数据
recvHttpRequest(fd, epfd);
}
}
}
return 0;
}
int acceptClient(int lfd, int epfd)
{
// 1. 建立连接
int cfd = accept(lfd, NULL, NULL);
if (cfd == -1)
{
perror("accept");
return -1;
}
// 2. 设置非阻塞
int flag = fcntl(cfd, F_GETFL);
flag |= O_NONBLOCK;
fcntl(cfd, F_SETFL, flag);
// 3. cfd添加到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");
return -1;
}
return 0;
}
int recvHttpRequest(int cfd, int epfd){//cfd客户端socket,epfd是epoll对象
int len = 0;
int total = 0;
char tmp[1024] = { 0 }; //用于读取
char buf[4096] = { 0 }; //存放整个http的请求
while ((len = recv(cfd, tmp, sizeof tmp, 0)) > 0)
{
if (total + len < sizeof buf)//buf数组读满了,无法再保存了
{
memcpy(buf + total, tmp, len);
}
total += len;
}
// 判断数据是否被接收完毕
if (len == -1 && errno == EAGAIN)//读完了
{
// 解析请求行
char* pt = strstr(buf, "\r\n");//返回‘\r’位置的指针,http数据包以'\r\n'进行换行
int reqLen = pt - buf;
buf[reqLen] = '\0';//手动截断buf数组,读取字符串时,遇到'\0'表示字符串结束
parseRequestLine(buf, cfd);//此时传入的buf就只是http数据包中的请求行
}
else if (len == 0)
{
// 客户端断开了连接
epoll_ctl(epfd, EPOLL_CTL_DEL, cfd, NULL);
close(cfd);
}
else
{
//recv函数出错了
perror("recv");
}
return 0;
}
// 解析请求行 line:请求行 cfd:客户端socket,分析完成后需要cfd进行数据发送
int parseRequestLine(const char* line, int cfd)
{
// 解析请求行 get /xxx/1.jpg http/1.1
char method[12];//get or post
char path[1024];//资源路径
sscanf(line, "%[^ ] %[^ ]", method, path);
printf("method: %s, path: %s\n", method, path);
decodeMsg(path, path);
printf("method: %s, path: %s\n", method, path);
if (strcasecmp(method, "get") != 0)//不区分大小写,进行字符串比较
{
return -1;
}
// decodeMsg(path, path);
// 处理客户端请求的静态资源(目录或者文件)
char* file = NULL;
if (strcmp(path, "/") == 0)
{
file = "./";
}
else
{
file = path + 1; //path 是数组,path+1:代表从第二个元素开始的数组
}
// 获取文件属性
struct stat st;
int ret = stat(file, &st);
if (ret == -1)
{
// 文件不存在 -- 回复404
sendHeadMsg(cfd, 404, "Not Found", getFileType(".html"), -1);//先发送http数据头
sendFile("404.html", cfd);//再发送get所需的文件
return 0;
}
// 判断文件类型
if (S_ISDIR(st.st_mode))
{
// 把这个目录中的内容发送给客户端
sendHeadMsg(cfd, 200, "OK", getFileType(".html"), -1);//发送的是html格式
sendDir(file, cfd);//发送目录
}
else
{
// 把文件的内容发送给客户端
sendHeadMsg(cfd, 200, "OK", getFileType(file), st.st_size);
sendFile(file, cfd);//再发送get所需的文件
}
return 0;
}
int sendFile(const char* fileName, int cfd)
{
// 1. 打开文件
int fd = open(fileName, O_RDONLY);
assert(fd > 0);
#if 0
while (1)
{
char buf[1024];
int len = read(fd, buf, sizeof buf);
if (len > 0)
{
send(cfd, buf, len, 0);
usleep(10); // 这非常重要,防止发送端发送数据太快了
}
else if (len == 0)//文件读取完毕
{
break;
}
else
{
perror("read");
}
}
#else
off_t offset = 0;
int size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
while (offset < size)
{
int ret = sendfile(cfd, fd, &offset, size - offset);//一次性无法发送完成,(size - offset)代表每次都希望能发完剩下的全部数据
printf("ret value: %d\n", ret);
if (ret == -1 && errno == EAGAIN)//写缓冲区满了
{
printf("没数据...\n");
}
}
#endif
close(fd);
return 0;
}
//status:状态码 descr:描述 type:文本类型 length:文本长度
int sendHeadMsg(int cfd, int status, const char* descr, const char* type, int length)
{
// 状态行
char buf[4096] = { 0 };
sprintf(buf, "http/1.1 %d %s\r\n", status, descr);
// 响应头
sprintf(buf + strlen(buf), "content-type: %s\r\n", type);
sprintf(buf + strlen(buf), "content-length: %d\r\n\r\n", length);
send(cfd, buf, strlen(buf), 0);
return 0;
}
int sendDir(const char* dirName, int cfd)
{
char buf[4096] = { 0 };//发送的内容
sprintf(buf, "<html><head><title>%s</title></head><body><table>", dirName);
struct dirent** namelist;
int num = scandir(dirName, &namelist, NULL, alphasort);
for (int i = 0; i < num; ++i)
{
// 取出文件名 namelist 指向的是一个指针数组 struct dirent* tmp[]
char* name = namelist[i]->d_name;
struct stat st;
char subPath[1024] = { 0 };//完整路径,相对路径
sprintf(subPath, "%s/%s", dirName, name);
stat(subPath, &st);
if (S_ISDIR(st.st_mode))//目录
{
// a标签 <a href="">name</a>
sprintf(buf + strlen(buf),
"<tr><td><a href=\"%s/\">%s</a></td><td>%ld</td></tr>",
name, name, st.st_size);
}
else
{//文件
sprintf(buf + strlen(buf),
"<tr><td><a href=\"%s\">%s</a></td><td>%ld</td></tr>",
name, name, st.st_size);
}
send(cfd, buf, strlen(buf), 0);
memset(buf, 0, sizeof(buf));
free(namelist[i]);
}
sprintf(buf, "</table></body></html>");
send(cfd, buf, strlen(buf), 0);
free(namelist);
return 0;
}
const char* getFileType(const char* name)
{
// a.jpg a.mp4 a.html
// 自右向左查找‘.’字符, 如不存在返回NULL
const char* 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";
}
// 将字符转换为整形数
int hexToDec(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;
}
// 解码
// to 存储解码之后的数据, 传出参数, from被解码的数据, 传入参数
void decodeMsg(char* to, char* from)
{
for (; *from != '\0'; ++to, ++from)
{
// isxdigit -> 判断字符是不是16进制格式, 取值在 0-f
// Linux%E5%86%85%E6%A0%B8.jpg
if (from[0] == '%' && isxdigit(from[1]) && isxdigit(from[2]))
{
// 将16进制的数 -> 十进制 将这个数值赋值给了字符 int -> char
// B2 == 178
// 将3个字符, 变成了一个字符, 这个字符就是原始数据
*to = hexToDec(from[1]) * 16 + hexToDec(from[2]);
// 跳过 from[1] 和 from[2] 因此在当前循环中已经处理过了
from += 2;
}
else
{
// 字符拷贝, 赋值
*to = *from;
}
}
*to = '\0';
}
①sendfile函数
Sendfile函数详解:
功能:sendfile函数用于高效传输文件内容,它直接将文件数据从文件系统发送到网络套接字,减少了数据在用户空间和内核空间之间的拷贝,提升了传输性能。
适用场景:特别适用于大文件传输场景,能显著降低CPU负载,提高传输效率。
函数原型:
ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);
out_fd:输出文件描述符,通常是套接字描述符。
in_fd:输入文件描述符,指向要传输的文件。
offset:文件偏移量,指定从文件的哪个位置开始传输。
count:要传输的字节数。
返回值:成功时返回传输的字节数,失败时返回错误码。
每次调用sendfile时更新offset参数(内核会自动修改该值),返回的offset参数代表已经发送的数据的位置。
②scandir函数
scandir函数用于扫描指定目录下的文件和子目录,返回一个包含这些条目信息的数组或列表。
函数原型:
int scandir(const char *dir, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compare)(const struct dirent ‌**, const struct dirent **‌));
dir:目标目录路径
namelist:存储结果的指针数组(需三级指针)
filter:过滤函数,返回非0则保留条目
compare:排序函数(如alphasort)
在C语言中,scandir会动态分配内存存储结果(namelist数组及其指向的结构体),使用后需手动释放以避免内存泄漏:
free(namelist[i])
free(namelist)
③sscanf函数
sscanf函数是C语言标准库中用于从字符串读取格式化输入的函数,其功能类似于scanf,但输入源是字符串而非标准输入。以下是关键点总结:
函数原型
int sscanf(const char *str, const char *format, ...);
str:待解析的源字符串。
format:格式控制字符串,指定如何解析数据。
可变参数:接收解析结果的指针。
返回值
成功时返回匹配并赋值的参数个数。
失败返回-1(错误存于errno)或0(无匹配)。
核心功能
提取数据:从字符串中读取整数、浮点数、字符串等。
高级匹配:类似于正则表达式
%[a-z]:仅匹配字母。
%[-9]:匹配非数字字符。
%*d:跳过整数(不存储)。
%4s:限制读取宽度(安全防止溢出)。
代码中有:
sscanf(line, "%[^ ] %[^ ]", method, path);//中间有个空格,表示跳过一个空格
%[^ ]
:代表非空格
server.h
#pragma once
// 初始化监听的套接字
int initListenFd(unsigned short port);
// 启动epoll
int epollRun(int lfd);
// 和客户端建立连接
int acceptClient(int lfd, int epfd);
// void* acceptClient(void* arg);
// 接收http请求
int recvHttpRequest(int cfd, int epfd);
// void* recvHttpRequest(void* arg);
// 解析请求行
int parseRequestLine(const char* line, int cfd);
// 发送文件
int sendFile(const char* fileName, int cfd);
// 发送响应头(状态行+响应头)
int sendHeadMsg(int cfd, int status, const char* descr, const char* type, int length);
const char* getFileType(const char* name);
// 发送目录
int sendDir(const char* dirName, int cfd);
// 将字符转换为整形数
int hexToDec(char c);
// 解码
void decodeMsg(char* to, char* from);
实验
ubuntu:
gcc -o main *.c
./main 10000 /xxx/xxx
edge browser
http://192.168.1.107:10000/