【计算机网络】超级简单的适合练手的HTTP服务器

简单描述:

实现一个超级简单的HTTP服务器,只在网页上输出“Hello World!”,旨在熟悉HTTP协议,按照HTTP协议的要求构造数据,就能实现了!


源码:

http_hello.c:

#include <stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>

#define MAX 10240

void http_init(char* ip,int port){
    int fd = socket(AF_INET,SOCK_STREAM,0);
    if(fd<0){
        perror("socket");
        return;
  }

  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = inet_addr(ip);
  addr.sin_port = htons(port);

  int ret = bind(fd,(struct sockaddr*)&addr,sizeof(addr));
  if(ret<0){
    perror("bind");
    return;
  }

  ret = listen(fd,10);
  if(ret<0){
    perror("listen");
    return;
  }
  while(1){
    struct sockaddr_in client_addr;
    socklen_t len;
    int client_fd = accept(fd,(struct sockaddr*)&client_addr,&len);
    if(client_fd<0){
      perror("accept");
      continue;
    }
    //用一个足够大的缓冲区,可以直接将数据读完
    char input_buf[MAX]={0};
    ssize_t read_size = read(client_fd,input_buf,sizeof(input_buf)-1);
    if(read_size<0){
      perror("read");
      return;
    }
    printf("[Request] %s",input_buf);
    char buf[MAX]={0};
    const char* hello = "<h1>hello world!</h1>";
    sprintf(buf,"HTTP/1.0 200 OK\nContent-Length:%lu\n\n%s",strlen(hello),hello);
    write(client_fd,buf,strlen(buf));
  }
}

int main(int argc,char * argv[]){
  if(3 != argc){
    printf("error: ./server [ip]  [port]\n");
    return 1;
  }
  http_init(argv[1],atoi(argv[2]));
  return 0;
}

makefile:

http_hello:http_hello.c
    gcc -o $@ $^

.PHONY:clean

clean:
    rm http_hello

程序运行结果:

服务器端:

这里写图片描述

客户端:

这里写图片描述

【注】:上面的IP地址,写的是我的云服务器的地址,自己试着在网页里玩的话要写自己的服务器地址啊!

猜你喜欢

转载自blog.csdn.net/sofia_m/article/details/80962675