cpp
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/wait.h>
#include<string.h>
#include<error.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/time.h>
#include<sys/select.h>
#include<fcntl.h>
#include<arpa/inet.h>
#include<ctype.h>
#include <sys/epoll.h>
#define OPEN_MAX 1024
int init_listen_fd(int port,int epfd){
printf("进入init_listen_fd函数\n");
struct sockaddr_in serv_addr;
//创建套接字
int listenfd = socket(AF_INET,SOCK_STREAM,0);
if(listenfd == -1){
perror("socket error");
exit(1);
}
//设置端口复用
int opt = 1;
setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)); //端口复用
//绑定地址结构
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(port);
int ret = bind(listenfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
if(ret == -1){
perror("bind() error");
exit(1);
}
//设置最大监听数
ret = listen(listenfd,128);
if(ret == -1){
perror("listen() error");
exit(1);
}
//lfd添加到epoll树上
struct epoll_event ev; //tep:epoll_ctl参数
ev.events = EPOLLIN; ev.data.fd = listenfd; //指定lfd的监听事件为读
ret = epoll_ctl(epfd,EPOLL_CTL_ADD,listenfd,&ev); //将lfd及对应的结构体设置的到树上,efd可找到该树
if(ret == -1){
perror("epoll_ctl error");
exit(1);
}
return listenfd;
}
//建立连接
void do_accept(int lfd,int epfd){
char str[BUFSIZ];
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_len = sizeof(clnt_addr);
int cfd = accept(lfd,(struct sockaddr*)&clnt_addr,&clnt_addr_len); //接受连接
if(cfd == -1){
perror("accept() error");
exit(1);
}
//打印一下客户端地址
printf("received from %s at PORT %d\n",inet_ntop(AF_INET
,&clnt_addr.sin_addr,str,sizeof(str)),ntohs(clnt_addr.sin_port));
//设置套接字非阻塞
int flag = fcntl(cfd,F_GETFL);
flag |= O_NONBLOCK;
fcntl(cfd, F_SETFL,flag);
//将新节点cfd挂到 epoll 监听树上
struct epoll_event tep;
tep.events = EPOLLIN | EPOLLET; tep.data.fd = cfd;
int ret = epoll_ctl(epfd,EPOLL_CTL_ADD,cfd,&tep);//加入红黑树
if(ret == -1){
perror("epoll_ctl error");
exit(1);
}
}
//错误页面
void send_error(int cfd, int status, char *title, char *text){
printf("===========发生错误\n");
char buf[4096] = {0};
sprintf(buf,"HTTP/1.1 %d %s\r\n",status,title);//报头
sprintf(buf+strlen(buf),"Content-Type:text/html\r\n");
sprintf(buf+strlen(buf),"Content-Length:-1\r\n");//文件长度
sprintf(buf+strlen(buf),"Connection:close\r\n");
send(cfd,buf,strlen(buf),0);
send(cfd,"\r\n",2,0);
memset(buf,0,sizeof(buf));
sprintf(buf,"<html><head><title>%d %s</title></head>\n",status,title);
sprintf(buf+strlen(buf),"<body bgcolor=\"#cc99cc\"><h2 align=\"center\">%d %s</h4>\n",status,title);
sprintf(buf+strlen(buf),"%s\n",text);
sprintf(buf+strlen(buf),"<hr>\n</body>\n</html>\n");
send(cfd,buf,strlen(buf),0);
return;
}
//获取一行\r\n结尾的数据
int get_line(int cfd, char *buf, int size){
int i = 0;
char c = '\0';
int n;
while((i<size-1)&&(c != '\n')){
n = recv(cfd,&c,1,0);
if(n>0){
if(c == '\r'){
n = recv(cfd,&c,1,MSG_PEEK);
if((n>0)&&(c=='\n')){
recv(cfd,&c,1,0);
}else{
c = '\n';
}
}
buf[i]=c;
i++;
}else{
c = '\n';
}
}
buf[i] = '\0';
if(-1 == n){
i=n;
}
return i;
}
//断开连接
void disconnect(int cfd,int epfd){
int ret = epoll_ctl(epfd,EPOLL_CTL_DEL,cfd,NULL);
if(ret != 0){
perror("epoll_ctl error");
exit(1);
}
close(cfd);
}
//回发应答协议
/*
应答报文:
HTTP/1.1 200 ok
Content-Type:text/plain;charset=iso-8859-1
Content-Length:45
*/
void send_respond(int cfd,int no,char *disp,char *type,int len){//客户端fd,错误号,错误描述,回发文件类型,文件长度
char buf[1024] = {0};
sprintf(buf,"HTTP/1.1 %d %s\r\n",no,disp);//报头
sprintf(buf+strlen(buf),"%s\r\n",type); //文件类型
sprintf(buf+strlen(buf),"Content-Length:%d\r\n",len);//文件长度
int ret = send(cfd,buf,strlen(buf),0);
printf("ret=%d\n",ret);
send(cfd,"\r\n",2,0);
printf("\n应答报文:\n%s\n",buf);
}
//发送服务器本地文件给浏览器
void send_file(int cfd,const char *file){
int n = 0;
char buf[1024]={0};
//fd是打开服务器的本地文件,cfd 是能访问客户端的socket
int fd = open(file,O_RDONLY);
if(fd == -1){
//404错误页面
perror("open error");
exit(1);
}
while((n = read(fd,buf,sizeof(buf))) > 0){
//printf("n ===== %d\n",n);
printf("读到数据:\n%s \n将要发给客户端\n",buf);
send(cfd,buf,strlen(buf),0);
}
close(fd);
}
//通过文件名获取文件的类型
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){
return "text/html;charset=utf-8";
}
if(strcmp(dot,".jpg") ==0 || strcmp(dot,"jpeg") == 0){
printf("==================图片类型\n");
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,".mp3") == 0){
return "audio/mpeg";
}
return "text/plain;charset=utf-8";
}
//处理http请求
void http_request(int cfd,const char *file){
struct stat sbuf;
//判断文件是否存在
int ret = stat(file,&sbuf);
if(ret != 0){
//回发浏览器 404 错误页面
send_error(cfd,404,"Not Found","NO such file or direntry");
return;
}
if(S_ISREG(sbuf.st_mode)){//是一个普通文件
printf("识别到 %s 普通文件\n",file);
//回发 http 协议应答
char Type[1024];
sprintf(Type,"%s%s%s","Content-Type:",get_file_type(file),"charset=iso-8859-1");
send_respond(cfd,200,"ok",Type,sbuf.st_size);
//回发 给客户端请求数据内容
send_file(cfd,file);
}else if(S_ISDIR(sbuf.st_mode)){
//是目录,待完善
}
}
//读取客户端请求报文
void do_read(int cfd,int epfd){
//读取一行http协议,拆分,获取 get 文件名 协议号
char line[BUFSIZ]={0};
int len = get_line(cfd, line, BUFSIZ);//读 http 请求协议首行 GET /hello.c HTTP/1.1
if(len == 0){
printf("服务器 检测到客户端关闭...\n");
disconnect(cfd,epfd);
}else{
char method[16],path[256],protocol[16];
sscanf(line,"%[^ ] %[^ ] %[^ ]",method,path,protocol);//拆分GET /hello.c HTTP/1.1 字符串进三个数组
printf("=====================Get请求报文===================\n");
printf("method=%s, path=%s, protocol=%s\n",method,path,protocol);
//清空报文缓冲,防止影响下一次读取
while(1){
char buf[1024] = {0};
len = get_line(cfd,buf,sizeof(buf));
if(len == '\n'){
break;
}else if(len == -1){
break;
}
//printf("%s\n",buf);
}
printf("=====================Get请求报文===================\n");
if(strncasecmp(method,"GET",3) == 0){//判断字符串相等 忽略大小写
char *file = path+1;
http_request(cfd,file);//处理请求
}
}
}
void epoll_run(int port){
struct epoll_event ep[OPEN_MAX]; //ep[]:epoll_wait参数
int i=0,nready;
int epfd = epoll_create(OPEN_MAX); //创建epoll模型,epfd指向红黑树节点
if(epfd == -1){
perror("epoll_create error");
exit(1);
}
//创建lfd,并添加至监听树
int lfd = init_listen_fd(port,epfd);
//printf("lfd添加红黑树成功\n");
while(1){
//监听节点对应事件
printf("开始阻塞监听\n");
nready = epoll_wait(epfd,ep,OPEN_MAX,-1);//阻塞监听
if(nready == -1){
perror("epoll_wait error");
exit(1);
}
for(i=0; i<nready; i++){
//只处理读事件,其他事件默认不处理
struct epoll_event *pev = &ep[i];
//不是读事件
if(!(pev->events & EPOLLIN)){
continue;
}
if(pev->data.fd == lfd){//接受连接请求
printf("监听到连接请求\n");
do_accept(lfd,epfd);
}else{//读数据
printf("监听到通信请求\n");
do_read(pev->data.fd,epfd);
}
}
}
}
int main(int argc,char *argv[]){
//命令行参数获取 端口 和 server提供的目录
if(argc < 3){
printf("./server_port path\n");
}
//获取用户输入的端口
int port = atoi(argv[1]);
//改变进程工作目录
int ret = chdir(argv[2]);
if(ret !=0){
perror("chdir error");
exit(1);
}
//启动epoll监听
epoll_run(port);
return 0;
}
项目待解决问题:
仅只能访问文件,访问音频视频会出错(怀疑报文文件类型有问题)
不能访问目录(未完善)