Home  >  Article  >  Web Front-end  >  Detailed introduction of web server

Detailed introduction of web server

PHP中文网
PHP中文网Original
2017-06-21 10:58:281824browse

1. HTTP protocol introduction

HTTP is the abbreviation of Hyper Text Transfer Protocol. Its development is the result of cooperation between the World Wide Web Consortium and the Internet Engineering Task Force (IETF), which eventually released a series of RFCs. RFC 1945 defines the HTTP/1.0 version. The most famous of these is RFC 2616. RFC 2616 defines a version commonly used today - HTTP 1.1.

HTTP protocol (HyperText Transfer Protocol, Hypertext Transfer Protocol) is a transfer protocol used to transfer hypertext from the WWW server to the local browser. It can make the browser more efficient and reduce network transmission. It not only ensures that the computer transmits hypertext documents correctly and quickly, but also determines which part of the document is transmitted and which part of the content is displayed first (such as text before graphics), etc.

  • HTTP is a communication protocol based on TCP/IP to transfer data (HTML files, image files, query results, etc.).

  • HTTP is an application layer protocol, consisting of requests and responses, and is a standard client-server model.

  • HTTP is a stateless protocol.

![Upload Deep understanding of HTTP protocol.jpg failed. Please try again.]


HTTP protocol is always the client Initiate a request and the server sends back a response.


This limits the use of the HTTP protocol, and it is impossible for the server to push messages to the client when the client does not initiate a request.
HTTP protocol is a stateless protocol. There is no correspondence between this request and the last request of the same client.

2.http protocol analysis

1.Browser request


http request method


We can correspond to the CRUD addition, deletion, modification and query operations of the database:

  1. CREATE: PUT

  2. READ: GET

  3. UPDATE:POST

  4. DELETE:DELETE

2. Server response

HTTP response points There are two parts: Header and Body (Body is optional). The most important lines of the Header we see in the Network are as follows:
HTTP/1.1 200 OK
200 indicates a successful response, and the following OK is illustrate.
If the returned value is not 200, there are often other functions, such as

  • The failed response is 404 Not Found: the web page does not exist

  • 500 Internal Server Error: Server internal error

  • ...Wait...


HTTP status code.jpg


Content-Type: text/html
Content-Type indicates the content of the response, here text/html represents the HTML web page.

3. Browser parsing process

When the browser reads the HTML source code of Sina's homepage, it will parse the HTML, display the page, and then, based on the various links in the HTML, Send an HTTP request to the Sina server, get the corresponding pictures, videos, Flash, JavaScript scripts, CSS and other resources, and finally display a complete page.

3. Summary

1. HTTP request process

After tracking Sina’s homepage, let’s summarize the HTTP request process:

Step 1: The browser first sends an HTTP request to the server. The request includes:

Method: GET or POST, GET only requests resources, POST will be accompanied by user data;
Path: /full/url/path;
Domain name: Specified by the Host header: Host: www.sina.com
and other related Headers;
If it is POST, the request also includes a Body, including user data

Step 2: Server Return an HTTP response to the browser. The response includes:

Response code: 200 means success, 3xx means redirection, 4xx means there is an error in the request sent by the client, and 5xx means an error occurred during server-side processing;
Response type: specified by Content-Type;
and other related Headers;
Usually the server's HTTP response will carry content, that is, there is a Body, containing the content of the response, and the HTML source code of the web page is in the Body .

Step 3: If the browser needs to continue to request other resources from the server, such as pictures, make another HTTP request and repeat steps 1 and 2.

The HTTP protocol adopted by the Web adopts a very simple request-response model, which greatly simplifies development. When we write a page, we only need to send the HTML in the HTTP request, and do not need to consider how to attach pictures, videos, etc. If the browser needs to request pictures and videos, it will send another HTTP request. Therefore, an HTTP The request only processes one resource (this can be understood as a short connection in the TCP protocol. Each link only obtains one resource. If you need more, you need to establish multiple links)
HTTP protocol also has strong scalability , although the browser requests the homepage, Sina can link resources from other servers in HTML, such as![](http://upload-images.jianshu.io/upload_images/6078268-6060a9b222ef1412.png?imageMogr2/ auto-orient/strip%7CimageView2/2/w/1240), thereby dispersing the request pressure to various servers, and one site can link to other sites, and countless sites are linked to each other, forming the World Wide Web, referred to as WWW.

2.HTTP format


Client request information

Server response Message
  • Each HTTP request and response follows the same format. An HTTP contains two parts: Header and Body, of which Body is optional.

  • HTTP protocol is a text protocol, so its format is also very simple.
    HTTP GET request format:
    GET /path HTTP/1.1
    Header1: Value1
    Header2: Value2
    Header3: Value3
    Each Header is one line, and the newline character is \r \nOr use os.linesep
    HTTP POST request format:
    POST /path HTTP/1.1
    Header1: Value1
    Header2: Value2
    Header3: Value3

    body data goes here...
    When two consecutive \r\n are encountered, the Header part ends, and all subsequent data is Body.
    HTTP response format:
    200 OK
    Header1: Value1
    Header2: Value2
    Header3: Value3

    body data goes here...
    HTTP response if Including body, also separated by \r\n\r\n.
    Please note again that the data type of the Body is determined by the Content-Type header. If it is a web page, the Body is text. If it is a picture, the Body is the binary data of the picture.
    When Content-Encoding exists, the Body data is compressed. The most common compression method is gzip. Therefore, when you see Content-Encoding: gzip, you need to decompress the Body data first to get the real data. The purpose of compression is to reduce the size of the Body and speed up network transmission.

    4Web static server

    1. Display fixed page

import socketimport multiprocessingimport osimport timedef serverHandler(clientSocket, clientAddr):'与请求的客户端进行交互'# 接收客户端发来的消息
    recvData = clientSocket.recv(1024).decode('utf-8')
    print(recvData)# 服务端向客户端发消息,作为响应
    responseLine = 'HTTP/1.1 200 OK' + os.linesep
    responseHeader = 'Server: laowang' + os.linesep
    responseHeader += 'Date: %s' % time.ctime() + os.linesep
    responseBody = '差一点一米八'
    sendData = (responseLine + responseHeader + os.linesep + responseBody).encode('gbk')

    clientSocket.send(sendData)# 关闭
    clientSocket.close()def main():'程序入口'# socket对象
    serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 绑定的端口号,可以重复使用端口号#serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)# 绑定
    serverSocket.bind(('', 8000))# 监听
    serverSocket.listen()while True:# 接收
        clientSocket, clientAddr = serverSocket.accept()
        print(clientSocket)# 开一个新的进程,执行交互
        multiprocessing.Process(target=serverHandler, args=(clientSocket, clientAddr)).start()# 关闭客户端对象
        clientSocket.close()if __name__ == '__main__':
    main()

Client browser page

2. Display the required page

import time,multiprocessing,socket,os,re

G_PATH = './html'

def serveHandler(clientSocket,clientAddr):
    recvData = clientSocket.recv(1024).decode('gbk')
    lineFirst = recvData.splitlines()[0]
    strFirst = re.split(r' +',lineFirst)
    fileName = strFirst[1]

    filePath = G_PATHif '/'== fileName:
        filePath += './index.html'else:
        filePath += fileNametry:file = Nonefile =open(filePath,'r',encoding='gbk')
        responseBody = file.read()

        responseLine = 'HTTP/1.1 200 OK' + os.linesep
        responseHeader = 'Server: ererbai' + os.linesep
        responseHeader += 'Date:%s' % time.ctime() + os.linesep
    except FileNotFoundError:
        responseLine = 'HTTP/1.1 404 NOT FOUND' + os.linesep
        responseHeader = 'Server: ererbai' + os.linesep
        responseHeader += 'Date:%s' % time.ctime() + os.linesep
        responseBody = '很抱歉,服务器中找不到你想要的内容'
    except Exception:
        responseLine = 'HTTP/1.1 500 ERROR' + os.linesep
        responseHeader = 'Server: ererbai' + os.linesep
        responseHeader += 'Date: %s' % time.ctime() + os.linesep
        responseBody = '服务器正在维护中,请稍后再试。'finally:if file!=None and not file.closed:file.close()

        senData = (responseLine + responseHeader + os.linesep + responseBody).encode('gbk')
        clientSocket.send(senData)
        clientSocket.close()


def main():
    serveSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    serveSocket.bind(('',8000))
    serveSocket.listen()while True:
        clientSocket,clientAddr = serveSocket.accept()
        print(clientSocket)
        multiprocessing.Process(target=serveHandler,args=(clientSocket,clientAddr)).start()
        clientSocket.close()if __name__ == '__main__':
    main()

Client browser home page

Client browser biye.html page


If you encounter any problems during the learning process or want to obtain learning resources, welcome to join the learning exchange group
343599877, let’s learn front-end together!

The above is the detailed content of Detailed introduction of web server. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn