In the actual development, although multi-threaded multi-process efficiency is very high, but when the server is faced with many concurrent, massive access, it is impossible to say that the establishment of so many processes, threads, but through a smaller granularity of the coroutine way to achieve, so that the use of CPU resources can be higher.

Network communication is based on TCP protocol to transmit data, and the communication between the server and the browser is based on HTTP protocol, so the following implementation of a coroutine TCP server based on Python, the browser can send requests and parse based on HTTP protocol. The browser displays a standard HTML page returned, and the server interprets multiple requests from the client and returns the result. That is, the client sends HTTP requests to the server according to various links in THE HTML to get the corresponding images, videos, Flash, JavaScript scripts, CSS and other resources, and finally displays a complete page

1. Implement the HTTP server in coroutine mode

import socket
import re
import gevent
from gevent import monkey

monkey.patch_all()


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).decode("utf-8")
    # print(">>>"*50)
    # print(request)

    request_lines = request.splitlines()
    print("")
    print(">" * 20)
    print(request_lines)

    # GET/index. HTTP / 1.1 HTML
    # get post put del
    file_name = ""
    ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
    if ret:
        file_name = ret.group(1)
        # print("*"*50, file_name)
        if file_name == "/":
            file_name = "/index.html"

    # 2. Return HTTP data to the browser

    try:
        f = open("./html" + file_name, "rb")
    except:
        response = "HTTP / 1.1 404 NOT FOUND \ r \ n"
        response += "\r\n"
        response += "------file not found-----"
        new_socket.send(response.encode("utf-8"))
    else:
        html_content = f.read()
        f.close()
        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"

        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)

    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)
    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
        gevent.spawn(service_client, new_socket)

        # new_socket.close()

    Close the listening socket
    tcp_server_socket.close()


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

Also through the browser to access the server, to achieve all the above functions, if it is a high concurrency access, the effect is more obvious. The HTTP server parses and responds to the HTTP sub page.

Scream tips:

Core relationships: processes, threads, coroutines can all implement multitasking

A process is a unit of resource allocation

Threads are the unit of operating system scheduling

Process switching requires the most resources and is inefficient

Thread switching requires average resources and efficiency (without the GIL, of course)

Coroutine switching task has small resources and high efficiency

Multi-process, multi-thread depending on the number of CPU cores may be parallel, but the coroutine is in one thread, so it is concurrent

Unified statement: About the original blog content, there may be some content reference from the Internet, if there is an original link will be quoted; If can not find the original link, in this statement if there is infringement please contact to delete ha. About reprint blog, if have original link will declare; If can not find the original link, in this statement if there is infringement please contact to delete ha.