• webserver项目


    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include 
    #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,"%d %s\n",status,title);
        sprintf(buf+strlen(buf),"

    %d %s

    \n"
    ,status,title); sprintf(buf+strlen(buf),"%s\n",text); sprintf(buf+strlen(buf),"
    \n\n\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; }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333

    项目待解决问题:
    仅只能访问文件,访问音频视频会出错(怀疑报文文件类型有问题)
    不能访问目录(未完善)

  • 相关阅读:
    用【mysql,vue,node】制作一个前后端分离小项目
    Spring6--IOC反转控制 / 基于XML管理bean
    MySQL性能优化 - 别再只会说加索引了
    【C++之数组与指针2】利用指针对数组求和
    LeetCode34.在排序数组中查找元素的第一个和最后一个位置
    C++实现:求平方根,输入一个实数x 计算并输出平方根(要求保留2位小数)
    VEX —— Functions|Volume
    C++中如何使用通用字符名输入UNICODE字符
    go语言 | 图解反射(二)
    神经网络 设计层数和神经元数量的考虑
  • 原文地址:https://blog.csdn.net/Anterior_condyle/article/details/133822677