Because the communication between networks is based on TCP protocol, and the communication between the server and the browser is based on HTTP protocol, the following implementation of a TCP server based on Python, the browser can send requests and parse based on HTTP protocol. The display browser returns a fixed page and an HTML page case.

1. The server can only return a fixed page to the requester

import socket


def handle_client(client_socket) :
    "Serving a client"
    recv_data = client_socket.recv(1024).decode("utf-8")
    request_header_lines = recv_data.splitlines()
    for line in request_header_lines:
        print(line)

    Organize the corresponding header information.
    response_headers = "HTTP / 1.1 200 OK \ r \ n"  # 200 indicates that the resource was found
    response_headers += "\r\n"  Separate the body with an empty line
    # Organization (body)
    response_body = "hello world"

    response = response_headers + response_body
    client_socket.send(response.encode("utf-8"))
    client_socket.close()


def main() :
    "As the main control entry for the program."

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    Port 7788 is bound to port 7788 the next time you run the program
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(("".7788))
    server_socket.listen(128)
    while True:
        client_socket, client_addr = server_socket.accept()
        handle_client(client_socket)


if __name__ == "__main__":
    main()
Copy the code

Use the Network Debugger as a TCP client to send a request to the server, and the server will invariably return hello,world based on the HTTP protocol format to all requesters.

If you use a browser to access the server over HTTP, the server returns hello,world to all requesters. Because the browser can parse HTTP format files, it can display Hello,world as a web page. Of course, if the browser returns a complete web page, then the browser can also parse the entire web page, which is our daily use of the server and browser based on HTTP protocol communication.

2. The server returns a web page to the requester

The browser requests the TCP server through HTTP. The server returns a web page to the browser. The browser parses the page and displays it in the front end.

import socket

def service_client(new_socket) :
    "" return data for this client. ""

    # 1. Receive requests from the browser, which are HTTP requests
    # GET / HTTP/1.1
    #...
    request = new_socket.recv(1024)
    print("> > >" * 50)
    print(request)

    # 2. Return HTTP data to the browser
    Data to be sent to the browser --header
    response = "HTTP / 1.1 200 OK \ r \ n"
    response += "\r\n"
    Data to be sent to the browser --boy
    # response += "hahahhah"

    f = open("./html/index.html"."rb")  # This is the test file we put in the current directory of the program in advance.
    html_content = f.read()
    f.close()

    Send the response header to the browser
    new_socket.send(response.encode("utf-8"))
    Send the response body to the browser
    new_socket.send(html_content)  Send data is not encode, open file is rb, binary format

    Close the socket
    new_socket.close()


def main() :
    """ To complete the overall control. """
    # 1. Create a socket
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Port 7890 is bound the next time the program is run
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 2. Binding
    tcp_server_socket.bind(("".7890))

    # 3. Becomes a listening socket
    tcp_server_socket.listen(128)

    while True:
        # 4. Waiting for the new client link
        new_socket, client_addr = tcp_server_socket.accept()

        # 5. Serve this client
        service_client(new_socket)

    Close the listening socket
    tcp_server_socket.close()


if __name__ == "__main__":
    main()
Copy the code

Use a browser to access the server, because what I’m defining here is that the server returns a fixed page (the page that we put on the server in advance). So as long as you’re accessing this server, this port, everything returns the same. So, you can access web site, any definition, will not affect the results of this visit, such as http://127.0.0.1:7890/dfsdf/aaaa, http://127.0.0.1:7890/aaa/index, etc. The results are the same. Because the server does not parse the client access link (file content), I give you this result no matter what you want.

The following server-side print shows the browser’s GET request, but notice that we actually visited once, but the server shows that the browser sent multiple GET requests. Why?

Scream tips: When the browser reads the HTML source code of the index home page, it parses the HTML and displays the page. Then, according to the various links in the HTML, it sends HTTP requests to the server to get the corresponding images, videos, Flash, JavaScript scripts, CSS and other resources, and finally displays a complete page. So we see a lot of additional HTTP requests below.

D:\software\python3\python.exe D:/pythoyworkspace/file_demo/Class_Demo/pachong/urllib_Request_Post.py >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>B 'get/HTTP/1.1\r\nHost: 127.0.0.1:7890\r\nConnection: keep-alive\r\ ncache-control: Max-age =0\r\ upgrade-insecure -Requests: 1\r\ nuser-agent: Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml; Q = 0.9, image/webp image/apng, * / *; Q = 0.8, application/signed - exchange; v=b3\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: zh-CN,zh; Q = 0.9 \ r \ n \ r \ n '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>B 'get /classic. CSS HTTP/1.1\r\nHost: 127.0.0.1:7890\r\nConnection: keep-alive\r\ nuser-agent: Mozilla / 5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36\r\nAccept: text/ CSS,*/*; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36\r\nAccept: text/ CSS,*/*; Q =0.1\r\ nAccept-encoding: http://127.0.0.1:7890/\r\ naccept-encoding: gzip, deflate, br\r\ nAccept-language: zh-cn,zh; Q = 0.9 \ r \ n \ r \ n '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>HTTP/1.1\r\nHost: 127.0.0.1:7890\r\nConnection: keep-alive\r\ nuser-agent: HTTP/1.1\r\nHost: 127.0.0.1:7890\r\nConnection: keep-alive\r\ nuser-agent: Mozilla / 5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36\r\nAccept: image/webp,image/apng,image/*,*/*; Q =0.8\r\ naccept-Encoding: http://127.0.0.1:7890/\r\ naccept-encoding: gzip, deflate, br\r\ nAccept-language: zh-cn,zh; Q = 0.9 \ r \ n \ r \ n '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>HTTP/1.1\r\nHost: 127.0.0.1:7890\r\nConnection: keep-alive\r\ nuser-agent: HTTP/1.1\r\nHost: 127.0.0.1:7890\r\nConnection: keep-alive\r\ nuser-agent: Mozilla / 5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36\r\nAccept: image/webp,image/apng,image/*,*/*; Q =0.8\r\ naccept-Encoding: http://127.0.0.1:7890/\r\ naccept-encoding: gzip, deflate, br\r\ nAccept-language: zh-cn,zh; Q = 0.9 \ r \ n \ r \ n '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>B 'GET /favicon. Ico HTTP/1.1\r\nHost: 127.0.0.1:7890\r\nConnection: keep-alive\r\ nuser-agent: Mozilla / 5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36\r\nAccept: image/webp,image/apng,image/*,*/*; Q =0.8\r\ naccept-Encoding: http://127.0.0.1:7890/\r\ naccept-encoding: gzip, deflate, br\r\ nAccept-language: zh-cn,zh; Q = 0.9 \ r \ n \ r \ n '
Copy the code

Scream tip: Although the client should parse the HTML, the root will send HTTP requests to the server according to the links in the HTML, get the corresponding images, videos, Flash, JavaScript scripts, CSS and other resources, and finally display a complete page. But we see below the actual return of the page there are ICONS (pictures) are missing, not displayed, why?

This is because although the client sends these resource requests to our server, our server does not parse these requests and return them to the client browser according to the requested file content. Therefore, in order to let the client implementation get the corresponding pictures, videos, Flash, JavaScript scripts, CSS and other resources, Finally, a complete page is displayed, and we need to redefine the server’s parsing function for the client’s request, as described in the next series of 2 blogs.