--- computer network and application layer HTTP protocol

The network layer is in contact with one of the largest level programmers, application layer is the hierarchy of the uppermost level, we do most of the processing logic.

  • Functional application layer
  • What is the url
  • http protocol

Function application layer
is the programmer to write the actual problems are solved one by one at the application layer, is the logical and do business processing locations.

What is the url
Uniform Resource Locator.
Including the name of the protocol: // username: password @ server address: port server / resource path / query string / fragment identifier
https://blog.csdn.net/boke_fengwei
such a site above is a url.
https: protocol name
bolg.csdn.net : is the domain name, the corresponding IP address is
boke_fengwei: resource path.
Url is above contains some special characters, this time need to make special treatment, using coding and decoding. This is to prevent ambiguous data.
Urlencode encoding using
transition rule : the data into hexadecimal, then right to left, taking 4 (direct process when less than four), that did not make two, preceded%, encoded into a form of XY% It can be. % This is a logo that escaped url , at the end of time can be decoded.
Interested in children's shoes can look urlencode function and implementation urldecode

HTTP protocol
HTTP request format
Here Insert Picture Description

Request line :

  • Common request methods
    GET : Gets resource
    POST : transport entity subject
    PUT : transfer files
    the HEAD : get the message header
    OPTIONS: inquiry support method
    DELETE: Delete files
    LINK: establish and link between the resources
    most commonly used is GET and POST
    GET submitted content in the url, in the POST request body examination.
  • Protocol Version

HTTP1.1 default long connection, which can effectively reduce the overhead of the TCP three-way handshake. HTTP
1.1 supports sending only header information (without any body of information), if the server thinks the client has permission request to the server, it returns 100, 401 otherwise. If the client receives 100, it began to send requests to the server body. When the server 401 so that, when returned, the client can not send the request body, saving bandwidth. Also part of HTTP also supports transferring content. Thus when the client has a portion of resources, the server requests additional simply keep some of the resources to. This is the basis of supporting documents HTTP.
HTTP1.0 is not a domain host, HTTP1.1 only support this argument.
HTTP2.0 using multiplexing (Multiplexing), allowing simultaneous multiplexed through a single HTTP / 2 multiple connection initiation request - response message.
"HTTP1.1 at the same time there is a limit to the number of domain name with a request exceeds the limit will block the request." Multiplexing underlying the use of "binary framing layer increases" method, so as not to change the original semantics, improve the transmission performance of the case where the header field, reduce latency.
All the binary transmission information frame is divided into smaller frames, encoded binary, a plurality of requests in the same TCP connection is completed, can carry any number of bidirectional data flow. HTTP / 2 more efficient use of the TCP connection, to obtain performance improvement.

Request header

  • Common header information
    (1) Content-Type: Data Type (text / html), etc.
    (2) Content-Length: length of the Body
    (3) Host: client tells the server that the requested resource in which the host port
    (4) user-Agent: version information statement user's operating system and browser
    (5) referer: the current page is to jump from that page over
    (6) location: forwarding information
    (7) Cookie: user client small amount of information stored
    blank line : " \ R & lt \ n- " blank lines is essential, is important to distinguish between a request header and a request flags body

HTTP response format
Here Insert Picture Description

Response line

  • Protocol version: the request line and protocol version of the same
  • Status Code: is a request that we return after the state flag after we had made the request things
    1XX: informational status code
    2XX: success status code
    3XX: Redirection status code
    4XX: Client Error status code
    5XX: server processes the request error
    common status code and state code interpreter
    200 OK: the hallmarks of our successful visit
    404 nOT fOUND: we did not find signs content
    403 FORBIDDEN: marks are still
    302 rEDIRECT: redirect.
    504 BADGATEWAY: bad gateway

Response header: request information and similar
blank lines: role of blank lines also mark the end of the response header, and response header to distinguish response body
response body: after the content returned in response.

Implement a simple HTTP server. That is, a display hello word statement when accessing our IP address.
Tcp connection before we implemented c ++ header files

  1 #include <string>
  2 #include <stdio.h>
  3 #include <unistd.h>
  4 #include <stdlib.h>
  5 #include <errno.h>
  6 #include <string.h>
  7 #include <netinet/in.h>
  8 #include <arpa/inet.h>
  9 #include <sys/socket.h>
 10 
 11 #define CHECK_RET(q) if((q) == false){return -1;}
 12 
 13 typedef struct calculator_info_t{
 14     int num1;
 15     int num2;
 16     char op;
 17 }calculator_info;
 18 
 19 class TcpSocket
 20 {
 21     public:
 22         TcpSocket() : _sockfd(-1){
 23         }
 24         void SetSockFd(int fd){
 25             _sockfd = fd;
 26         }
 27         int GetSockFd(){
 28             return _sockfd;
 29         }
 30         bool Socket() {
 31             _sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 32             if (_sockfd < 0) {
 33                 perror("socket error");
 34                 return false;
 35             }
 36             return true;
 37         }
 38         bool Bind(std::string &ip, uint16_t port){
 39             struct sockaddr_in addr;
 40             addr.sin_family = AF_INET;
 41             addr.sin_port = htons(port);
 42             addr.sin_addr.s_addr = inet_addr(ip.c_str());
 43 
 44             socklen_t len = sizeof(struct sockaddr_in);
 45             int ret = bind(_sockfd, (struct sockaddr*)&addr, len);
 46             if (ret < 0) {
 47                 perror("bind error");
 48                 return false;
 49             }
 50             return true;
 51         }
 52         bool Listen(int backlog = 10) {
 53             //int listen(int sockfd, int backlog);
 54             //backlog:最大并发连接数--内核中已完成连接队列的最大节点数
 55             int ret = listen(_sockfd, backlog);
 56             if (ret < 0) {
 57                 perror("listen error");
 58                 return false;
 59             }
 60             return  true;
 61         }
 62         bool Connect(std::string &ip, uint16_t port) {
 63             //int connect(int fd, struct sockaddr *addr,socklen_t len);
 64             //addr: 要连接的服务端地址信息
 65             struct sockaddr_in addr;
 66             addr.sin_family = AF_INET;
 67             addr.sin_port = htons(port);
 68             addr.sin_addr.s_addr = inet_addr(ip.c_str());
 69             socklen_t len = sizeof(struct sockaddr_in);
 70 
 71             int ret = connect(_sockfd, (struct sockaddr*)&addr, len);
 72             if (ret < 0) {
 73                 perror("connect error");
 74                 return false;
 75             }
 76             return true;
 77         }
 78         bool Accept(TcpSocket &csock, struct sockaddr_in *addr = NULL){
 79             //int accept(int sockfd, sockaddr *addr, socklen_t *len);
 80             //addr: 客户端的地址信息
 81             //len: 输入输出参数,既要指定接收长度,还要接收实际长度
 82             //返回值:为新客户端新建的socket套接字描述符
 83             //通过这个返回的描述符可以与指定的客户端进行通信
 84             struct sockaddr_in _addr;
 85             socklen_t len = sizeof(struct sockaddr_in);
 86             int newfd = accept(_sockfd, (struct sockaddr*)&_addr, &len);
 87             if (newfd < 0) {
 88                 perror("accept error");
 89                 return false;
 90             }
 91             if (addr != NULL) {
 92                 memcpy(addr, &_addr, len);
 93             }
 94             csock.SetSockFd(newfd);
 95             //_sockfd--仅用于接收新客户端连接请求
 96             //newfd----专门用于与客户端进行通信
 97             return true;
 98         }
 99         bool Recv(std::string &buf) {
100             char tmp[4096] = {0};
101             //ssize_t recv(int sockfd, void *buf, size_t len, int flags)
102             //flags:0-默认阻塞接收  MSG_PEEK-获取数据但是不从缓冲区移除
103             //返回值:实际接收的数据长度    失败:-1    连接断开:0
104             int ret = recv(_sockfd, tmp, 4096, 0);
105             if (ret < 0) {
106                 perror("recv error");
107                 return false;
108             }else if (ret == 0) {
109                 printf("peer shutdown\n");
110                 return false;
111             }
112             buf.assign(tmp, ret);
113             return true;
114         }
115         bool Send(std::string &buf) {
116             //ssize_t send(int sockfd, void *buf, size_t len, int flags)
117             int ret = send(_sockfd, buf.c_str(), buf.size(), 0);
118             if (ret < 0) {
119                 perror("send error");
120                 return false;
121             }
122             return true;
123         }
124         bool Close() {
125             close(_sockfd);
126             _sockfd = -1;
127         }
128     private:
129         int _sockfd;
130 };  

Achieve cpp file

  1 #include "tcpsocket.hpp"
  2 #include <iostream>
  3 #include <sstream>
  4 int main(int argc,char* argv[]){
  5     if(argc != 3){
  6         std::cout<<"./http_server ip port"<<std::endl;
  7         return -1;
  8     }
  9     std::string ip = argv[1];
 10     uint16_t port = atoi(argv[2]);
 11     TcpSocket sock;
 12     //1.创建套接字
 13     CHECK_RET(sock.Socket());
 14     //2.绑定连接
 15     CHECK_RET(sock.Bind(ip,port));
 16     //设置监听
 17     CHECK_RET(sock.Listen(10));
 18     //开始通信
 19     while(1){
 20         //首先创建一个sockaddr_in
 21         struct sockaddr_in client;
 22         TcpSocket cli;
 23         if(sock.Accept(cli,&client) == false){
 24             continue;
 25         }
 26         //接受连接请求
 27         std::string buf;
 28         cli.Recv(buf);
 29         std::cout<<"接受到的数据["<<buf<<"]"<<std::endl;
 30         //发送一个简单的页面请求
 31         //使用一个数据流来格式化数据
 32         std::string body;
 33         body = "<html><body><h1>hello world</h1></body></html>";
 34         std::stringstream ss;
 35         ss << "http/1.1 200 OK\r\n";//响应行
 36         ss << "Content_Length: "<<body.size()<<"\r\n";
 37         ss << "Content_Type: text/html"<<"\r\n";
 38         ss << "Location: http://www.baidu.com\r\n";
 39         ss<<"\r\n";
 40         std::string header = ss.str();
 41         cli.Send(header);
 42         cli.Send(body);
 43         cli.Close();
 44     }
 45     sock.Close();
 46     return 0;
 47 } 

Guess you like

Origin blog.csdn.net/boke_fengwei/article/details/91040424