☀️ Suzhou program big white uses ten thousand words to analyze Python Network Programming and Web programming ☀️ < ❤️ Remember to collect ❤️>

Posted by snascendi on Wed, 20 Oct 2021 08:29:20 +0200

catalogue

🏳️‍🌈 Let's talk!!!! 🏳️‍🌈 Suzhou program Dabai 🏳️‍🌈

🌟 Blogger introduction

💂 Personal home page: Suzhou program white
🤟 The author introduces: member of China DBA Alliance (ACDU) and administrator of program ape (yuan) gathering place of CSDN all over the country. Currently engaged in industrial automation software development. Good at C#, Java, machine vision, underlying algorithms and other languages. In 2019, Qiyue software studio was established.
💬 If the article is helpful to you, you are welcome to pay attention, like, collect (one click, three links) and subscribe to some columns such as C#, Halcon, python+opencv, VUE, interviews with major companies, etc
🎗️ Undertake various software development projects
💅 If you have any questions, you are welcome to send a private letter and will reply in time
👤 Micro signal: stbsl6, WeChat official account: Suzhou program whiten
🎯 Those who want to join the technical exchange group can add my friends. The group will share learning materials

Fundamentals of computer network

Introduction to IP address

Concept of IP address:

  • Internet Protocol Address refers to the Internet Protocol Address, which is also translated into Internet Protocol Address.

  • IP address is a unified address format provided by IP protocol. It assigns a logical address to each network and host on the Internet to shield the difference of physical address.

    Expression of IP address:

  • IP addresses fall into two categories: IPv4 and IPv6.

  • IPv4 is a widely used IP protocol.

  • IPv6 is a popular next-generation IP protocol in order to solve the problem of insufficient IPv4 address at this stage.

  • IPv4 is composed of dotted decimal.

  • IPv6 is composed of colon hexadecimal.

Role of IP address:

  • IP address is used to identify the only device in the network, that is, a device in the network can be found through IP address.

    View IP address:

  • Linux and mac OS use ifconfig.

  • Windows uses the ipconfig command

Port and port number

What is a port and what is a port number

  • That is, the channel for data transmission. If the IP address is compared to the address of a house, the port is the door to the house;

  • However, there are only a few doors in a real house, but there can be 65536 ports with an IP address;

  • Ports are marked by port numbers. Port numbers have only integers, ranging from 0 to 65535.

Classification of port numbers

  • Well known port: 0 - 1023.

  • Dynamic port: 1024 - 65535.

agreement

TCP protocol

  • Concept of TCP

  • Transmission Control Protocol is a connection oriented, reliable and byte stream based transport layer communication protocol.

TCP communication flow

1. Establish a connection (three handshakes).

2. Transmit data.

3. Close the connection (four waves).

Characteristics of TCP

  • Connection oriented.

  • Reliable transmission.

UDP protocol

  • Concept: User Datagram Protocol is a connectionless transport layer protocol in OSI reference model.

Characteristics of UDP

  • Message oriented.

  • No connection.

  • The throughput is not regulated by the congestion control algorithm.

socket

  • What is socket?
    Network socket (English: network socket; also translated into network socket, network interface and network slot) is the endpoint of inter process data flow in computer network in computer science. It is an inter process communication mechanism provided by operating system.

  • Function of socket
    Network data transmission between processes.

TCP network development process

TCP client program development process

  • Process sorting:

1. Create a server socket object.

2. Bind listening port.

3. Set listening.

4. Wait for the connection request from the client.

5. Accept data.

6. Return data.

7. Close the socket.

TCP server program development process

  • Process sorting:

1. Create a client socket object.

2. Establish a connection with the server socket.

3. Send data.

4. Accept data.

5. Close the client socket.

TCP network development

socket class

In Python, we use the socket() function to create sockets. The syntax format is as follows:

import socket

socket.socket([family[, type[, proto]]])
  • Parameters:
parameterdescribe
familyThe socket family enables AF_UNIX or AF_INET
familyThe socket family enables AF_UNIX or AF_INET
typeSocket types can be divided into sock types according to whether they are connection oriented or non connection oriented_ Stream or SOCK_DGRAM
protocolGenerally, it is not filled in, and the default value is 0
  • Socket type:
typedescribe
socket.AF_UNIXIt can only be used for inter process communication of a single Unix system
socket.AF_INETCommunication protocol between server and client (IPv4)
socket.AF_INET6Communication protocol between server and client (IPv6)
socket.SOCK_STREAMData transmission using TCP transmission protocol (streaming socket)
socket.SOCK_DGRAMUse UDP transmission protocol for data transmission (datagram socket)
socket.SOCK_RAWRaw socket; It can handle ICMP, IGMP and other special network messages that ordinary sockets cannot handle
socket.SOCK_RDMProvide reliable UDP datagram connection, that is, ensure the delivery of datagrams but not data
socket.SOCK_SEQPACKETProvide continuous and reliable packet connection
  • socket class method:
methoddescribe
_socket.bind(address)Bind the socket to the address; In AF_ Under INET, the address is represented in the form of tuple (host,port).
_socket.listen(backlog)Start listening for incoming connections. The backlog specifies the maximum number of connections that can be suspended before a connection is rejected.
_socket.setblocking(bool)Whether to block (True by default). If False is set, an error will be reported if there is no data in accept and recv.
_socket.accept()Accept the connection and return (conn,address), where conn is a new socket object that can be used to receive and send data. Address is the address of the client.
_socket.connect(address)Connect to the socket at address. Generally, the format of address is tuple (hostname,port). If there is a connection error, the socket.error error error is returned.
_socket.connect_ex(address)The same as above, but there will be a return value. 0 will be returned when the connection is successful, and an error code will be returned when the connection fails
_socket.close()Close socket connection
_socket.recv(bufsize[,flag])Accepts data from the socket. The data is returned as a string, and bufsize specifies the maximum number that can be received. flag provides additional information about the message, which can usually be ignored.
_socket.recvfrom(bufsize[.flag])Similar to recv(), but the return value is (data,address). Where data is the string containing the received data, and address is the socket address where the data is sent.
_socket.send(string[,flag])Sends the data in the string to the connected socket. The return value is the number of bytes to send, which may be less than the byte size of string. That is, the specified contents may not be sent in full.
_socket.sendall(string[,flag])Sends the data in the string to the connected socket, but attempts to send all the data before returning. None is returned successfully, and an exception is thrown if it fails. Internally, send is called recursively to send all contents.
_socket.sendto(string[,flag],address)Send data to the socket. Address is a tuple in the form of (ipaddr, port) and specifies the remote address. The return value is the number of bytes sent. This function is mainly used for UDP protocol.
_socket.settimeout(timeout)Set the timeout of socket operation. Timeout is a floating-point number in seconds. A value of None indicates that there is no timeout.
_socket.getpeername()Returns the remote address of the connection socket. The return value is usually a tuple (ipaddr,port).
_socket.getsockname()Returns the socket's own address. Usually a tuple (ipaddr,port)
_socket.fileno()File descriptor for socket

TCP client program development

import socket   # Import socket package
if __name__ == '__main__':
    # Create socket AF_ INET - > adopt IPv4; SOCK_ Stream - > adopt TCP transmission protocol
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Establish connection with the server
    client_socket.connect(('127.0.0.1', 9091))
    # Prepare the data to be sent and encode it with UTF-8
    _data = 'Connect Succces!'.encode('utf-8')
    # send data
    client_socket.send(_data)
    # Get the data returned by the server
    _recv = client_socket.recv(1024)
    # Print the original data returned by the server
    print('Get raw data from the server:', _recv)
    # Decode data
    _decode = _recv.decode('utf-8')
    print('Get data from server:', _decode)
    # Close socket
    client_socket.close()

TCP server program development

Single task version:

import socket # Import socket package
if __name__ == '__main__':
    # Create socket AF_ INET - > adopt IPv4; SOCK_ Stream - > adopt TCP transmission protocol
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Set and enable port multiplexing. When the program ends, release the port number immediately
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # Binding listening port number
    server_socket.bind(("0.0.0.0", 9091))
    # Configure the maximum number of connections waiting for listening
    server_socket.listen(128)
    # Wait for the client to establish a connection request and return (conn, info). If there is no connection, it will remain blocked all the time
    # Where conn is defined by service_socket receiving is a socket that establishes a connection with the client
    # info by client_info receiving is the address and port information of the client
    service_socket, client_info = server_socket.accept()
    print('Client IP Address and port number:', client_info)
    # Get the original data sent by the client
    _renv = service_socket.recv(1024)
    # Gets the length of the original data
    _length = len(_renv)
    print('The length of received data is:', _length)
    # Decode the original data
    _decode = _renv.decode('utf-8')
    print('The data received from the client is:', _decode)
    # Prepare the data to be returned and encode it with UTF-8
    _data = 'Problem handling...'.encode('utf-8')
    # send data
    service_socket.send(_data)
    # Close the socket between the server and the client
    service_socket.close()
    # Close the server socket
    server_socket.close()

Multitasking version:

In the real production environment, a server cannot serve only one client; Usually, a server should be able to serve multiple clients. The following is the implementation idea of multitasking:

1. Write a TCP server program and wait for the client to accept the connection request.

2. When the connection between the client and the server is successful, a sub thread is created, and the sub thread is used to process the client's request to prevent the main thread from blocking.

3. Set the created sub thread as the guardian main thread to prevent the main thread from exiting.

import socket
import threading
# Client service handler
def handle_client_request(_socket, _info):
    while True:
        # Get the original data sent by the client
        _data = _socket.recv(1024)
        # if statements can be directly used to judge whether there is data in the container type. if there is data in the container type, the condition is true, otherwise the condition fails
        # Container type: list, dictionary, tuple, string, set, range, binary data
        if _data:
            print(_data.decode("utf-8"), _info)
            # reply
            _socket.send("Data reception is normal...".encode("utf-8"))
        else:
            print("The client is offline:", _info)
            break
    # Close the socket between the server and the client
    _socket.close()

if __name__ == '__main__':
    # Create socket AF_ INET - > adopt IPv4; SOCK_ Stream - > adopt TCP transmission protocol
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Set and enable port multiplexing. When the program ends, release the port number immediately
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # Binding listening port number
    tcp_server_socket.bind(("", 9090))
    # Configure the maximum number of connections waiting for listening
    tcp_server_socket.listen(128)
    # Cycle waiting to receive the connection request from the client
    while True:
        # Wait for the client to establish a connection request and return (conn, info). If there is no connection, it will remain blocked all the time
        # Where conn is defined by service_socket receiving is a socket that establishes a connection with the client
        # info by client_info receiving is the address and port information of the client
        service_socket, client_info = tcp_server_socket.accept()
        print("Client connection succeeded:", client_info)
        # When the connection between the client and the server is successful, a sub thread is created to process the next client message
        client_thread = threading.Thread(target=handle_client_request, args=(service_socket, client_info))
        # Set the guard main thread to automatically terminate the child thread when the main thread exits
        client_thread.setDaemon(True)
        # Start child thread
        client_thread.start()

Network development considerations

1. When the TCP client program wants to communicate with the TCP server program, it must first establish a connection.

2. TCP client programs generally do not need to bind the port number, because the client initiates the connection actively.

3. The TCP server program must bind the port number, otherwise the client cannot find the TCP server program.

4. The socket after listen is a passive socket, which is only responsible for receiving connection requests from new clients and cannot send and receive messages.

5. When the TCP client program and the TCP server program are successfully connected, the TCP server program will generate a new socket, which will be used for sending and receiving client messages.

6. Closing the socket returned by accept means that communication with the client has been completed.

7. Closing the socket after listen ing means that the socket on the server is closed, which will cause new clients to be unable to connect to the server, but the previously successfully connected clients can still communicate normally.

8. When the socket of the client calls close, the recv of the server will unblock and the length of the returned data is 0. The server can judge whether the client has been offline by the length of the returned data. On the contrary, when the server closes the socket, the recv of the client will unblock and the length of the returned data is 0.

Analysis of the principle of send and recv in socket


send principle

Q: Does send send send data directly to the server?

A: No, if you want to send data, you must send data through the network card. The application cannot send data directly through the network card. It needs to call the operating system interface, that is, the application writes the sent data to the sending buffer (a space in memory), and then the operating system controls the network card to send the data in the sending buffer to the server network card.

recv principle

Q: Does renv receive data directly from the client?

A: No, the application software cannot directly receive data through the network card. It needs to call the operating system interface. The operating system receives data through the network card, writes the received data into the receiving buffer (a space in memory), and then the application obtains the data sent by the client from the receiving buffer.

HTTP protocol

What is the HTTP protocol

  • HTTP protocol introduction:

1. The full name of HTTP protocol is hypertext transfer protocol, which translates into hypertext transfer protocol.

2. Hypertext is the abbreviation of hypertext, which refers to exceeding text restrictions or hyperlinks. For example, pictures, music, videos, hyperlinks, etc. all belong to hypertext.

3. The producer of HTTP protocol is Tim Berners Lee, who designed it in 1991. Before the design of HTTP protocol, the purpose was to transmit web page data. Now it is allowed to transmit any type of data.

4. The transmission of data in HTTP protocol format is based on TCP transmission protocol. A connection needs to be established before sending data.

  • Functions of HTTP protocol:

1. Specify the data format for browser and web server communication.

  • Communication process of browser accessing Web server

What is a URL

What is a URL:

1. The English spelling of URL is uniform resource locator, which means uniform resource locator. It is commonly understood as the network resource address, which is what we often call the web address.

  • Composition of URL

What the URL looks like:

Components of URL:

1. Protocol Part: https: / /, http: / /, ftp: / /.

2. Domain name: news.163.com.

3. Resource path part: / 18/1122/10/E178J2O4000189FH.html.

Domain name:

  • The domain name is the alias of the IP address. It is a name divided by dots and composed of English letters and numbers. The purpose of using the domain name is to easily remember the IP address of a host.

URL extension:

  • The model complies with the Codable protocol.

  • Parse with JSONEncoder.

definition ConvertToStringable agreement
protocol ConvertToStringable {
    associatedtype Result: Codable
    var valueString: String { get }
}

extension ConvertToStringable {
    func toString(result: Result) -> String {
        let data = try? JSONEncoder().encode(result)
        guard let da = data else { return "" }
        guard let st = String.init(data: da, encoding: .utf8) else { return "" }
        return st
    }
}

We use association types to match different model instances, and then we extend the model in each model that needs to be converted into JSON format string:

struct UserInfo: Codable {
    var name: String
    var age: Int
    var avator: String
}

extension UserInfo: ConvertToStringable {
    typealias Result = UserInfo
    var valueString: String { return toString(result: self) }
}

Query parameter part:? page=1&count=10 ​

  • Parameter Description:

? The following page represents the first parameter, and the following parameters are connected with &.

HTTP request message

GET request message

---- Request line ----
GET / HTTP/1.1  # GET request resource path HTTP protocol version
---- Request header -----
Host: www.smartfox.cc  # The host address and port number of the server. The default is 80
Connection: keep-alive # Keep a long connection with the server
Upgrade-Insecure-Requests: 1 # Let the browser upgrade unsafe requests and use https requests
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36  # User agent, that is, the name of the client
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 # Acceptable data types
Accept-Encoding: gzip, deflate # Acceptable compression format
Accept-Language: zh-CN,zh;q=0.9 #Acceptable language
Cookie: csrftoken=ZIVKMSEdmdJbowTnXtRPXByIqxK1WF1ronGQXKWdp51WnSvmlRyqsKzZFPAojcLF; sessionid=as3sop6t2igilg76zll45m045udfsoa7; # Identity of the logged in user

---- Blank line ----

In other words, the GET request message is composed of the following parts:

  • Request line.

  • Request header.

  • Blank line.

POST request message

---- Request line ----
POST /admin.php?next=index.php HTTP/1.1 # POST request mode request resource path HTTP protocol version
---- Request header ----
Host: www.smartfox.cc # The host address and port number of the server. The default is 80
Connection: keep-alive # Keep a long connection with the server
Content-Type: application/x-www-form-urlencoded  # Tell the server the requested data type
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36 # Name of the client
---- Blank line ----
---- Request body ----
username=admin&pass=admin # Request parameters

In other words, the POST message is composed of the following parts:

  • Request line

  • Request header

  • Blank line

  • Request body

The difference between POST and GET

  • An HTTP request message can be composed of four parts: request line, request header, empty line and request body.

  • The request message of GET mode has no request body, only composed of request line, request header and empty line.

  • The POST mode request message can be composed of request line, request header, blank line and request body.

Note: POST mode allows no request body, but this format is rare. ​

HTTP response message

HTTP response message

--- Response line/Status line ---
HTTP/1.1 200 OK # HTTP protocol version status code status description
--- Response header ---
Server: Tengine # Server name
Content-Type: text/html; charset=UTF-8 # Content type
Transfer-Encoding: chunked # The length of the content sent to the client is uncertain. The mark at the end of sending is 0 \ R \ n. content length indicates that the server determines the size of the content sent to the client, but only one of them can be used.
Connection: keep-alive # Keep a long connection with the client
Date: Fri, 23 Nov 2018 02:01:05 GMT # Server response time
--- Blank line ---
--- Responder ---
<!DOCTYPE html><html lang="en">...</html> # Data in response to the client

Therefore, a mature HTTP response message is composed of the following parts:

Common HTTP status codes

Status codestateexplain
200OKRequest succeeded
201CreatedThe request has been implemented, the required resources have been established, and its URI has been returned with the header information.
202AcceptedThe server accepted the request but has not yet processed it.
307Temporary Redirectredirect
400Bad RequestWrong request, wrong request address or parameter
403ForbiddenThe server understood the request but refused to execute it.
404Not FoundThe requested resource does not exist on the server
500Internal Server ErrorServer internal source code error
502Bad GatewayWhen a server that is a gateway or proxy attempts to execute a request, it receives an invalid response from the upstream service.

Use the HTTP server that comes with Python

What is a static web server

  • A program that provides static documents to the requesting browser.

  • When we browse Baidu news data, the news data will change every day. The page we visit is dynamic, while what we develop is static, and the data of the page will not change.

How to build Python's own static Web server

In the module of Python 3, the http module is officially added. We can directly call and run it as a static Web service.

  • Syntax format: python3 -m http.server [PORT].

  • -m represents the modules in the operation package.

  • When executing this command, you need to enter the directory of the static file you specify, and then you can access the corresponding static file through the browser.

python3 -m http.server 8080

Self made static Web server

Return fixed page data

import socket

if __name__ == '__main__':
    _server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    _server.bind(("", 9091))

    _server.listen(10)

    while True:
        _client, _client_info = _server.accept()

        _request_data = _client.recv(4096)

        print(_request_data)

        with open("static/index.html", 'rb') as _file:
            file_data = _file.read()
            print(file_data)

        response_line = "HTTP/1.1 200 OK\r\n"

        response_head = "Server: NGINX/14.8\r\n"

        response_body = file_data

        response_data = (response_line + response_head + "\r\n").encode('utf-8') + response_body
        print(response_data)
        _client.send(response_data)

        _client.close()

Returns the specified page data

import socket


def init_server():
    _server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    _server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    _server.bind(("", 9091))
    print("Server Listen : 0.0.0.0:9091")
    _server.listen(128)
    return _server


def service_logic(_server):
    _service, _info = _server.accept()
    renv_data = _service.recv(4096)
    if len(renv_data) == 0:
        print('client', _info, 'off-line')
        _service.close()
        return

    _data = renv_data.decode('utf-8')
    url = _data.split(" ", maxsplit=2)

    uri = url[1]
    print(uri)

    if uri == "/":
        uri = '/index.html'

    try:
        with open("static" + uri, "rb") as _file:
            response_body = _file.read()
    except Exception as e:
        response_line = "HTTP/1.1 404 Not Found\r\n"

        response_header = "Server: PythonWeb1.0\r\n"
        with open("static/error.html", "rb") as _file:
            response_body = _file.read()

        response_data = (response_line + response_header + "\r\n").encode("utf-8") + response_body

        _service.send(response_data)
    else:
        response_line = "HTTP1.1 200 OK\r\n"

        response_header = "Server: PythonWeb1.0\r\n"
        response_data = (response_line + response_header + "\r\n").encode('utf-8') + response_body

        _service.send(response_data)
    finally:
        _service.close()


if __name__ == '__main__':
    server = init_server()
    while True:
        service_logic(server)

Multitasking version

import socket
import threading


def init_server():
    _server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    _server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    _server.bind(("", 9091))
    print("Server Listen : 0.0.0.0:9091")
    _server.listen(128)
    return _server


def handle_client(_service, _info):
    renv_data = _service.recv(4096)
    if len(renv_data) == 0:
        print('client', _info, 'off-line')
        _service.close()
        return

    _data = renv_data.decode('utf-8')
    url = _data.split(" ", maxsplit=2)

    uri = url[1]
    print(uri)

    if uri == "/":
        uri = '/index.html'

    try:
        with open("static" + uri, "rb") as _file:
            response_body = _file.read()
    except Exception as e:
        response_line = "HTTP/1.1 404 Not Found\r\n"

        response_header = "Server: PythonWeb1.0\r\n"
        with open("static/error.html", "rb") as _file:
            response_body = _file.read()

        response_data = (response_line + response_header + "\r\n").encode("utf-8") + response_body

        _service.send(response_data)
    else:
        response_line = "HTTP1.1 200 OK\r\n"

        response_header = "Server: PythonWeb1.0\r\n"
        response_data = (response_line + response_header + "\r\n").encode('utf-8') + response_body

        _service.send(response_data)
    finally:
        _service.close()


def service_logic(_server):
    _services, _info = _server.accept()

    handle_service = threading.Thread(target=handle_client, args=(_services, _info))
    handle_service.daemon = True
    handle_service.start()


if __name__ == '__main__':
    server = init_server()
    while True:
        service_logic(server)

Object oriented version

import socket
import threading


class WebServer(object):
    def __init__(self, addr: str = '0.0.0.0', port: int = 9091) -> None:
        self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self._server.bind((addr, port))
        print(f"Server Listen!{addr}:{port}")
        self._server.listen(128)

    def service_logic(self) -> None:
        while True:
            _services, _info = self._server.accept()
            handle_service = threading.Thread(target=self.handle_client, args=(_services, _info))
            handle_service.daemon = True
            handle_service.start()

    @staticmethod
    def handle_client(_service: socket.socket, _info: tuple) -> None:
        renv_data = _service.recv(4096)
        if len(renv_data) == 0:
            print('client', _info, 'off-line')
            _service.close()
            return

        _data = renv_data.decode('utf-8')
        url = _data.split(" ", maxsplit=2)

        uri = url[1]
        print(uri)

        if uri == "/":
            uri = '/index.html'

        try:
            with open("static" + uri, "rb") as _file:
                response_body = _file.read()
        except Exception as e:
            response_line = "HTTP/1.1 404 Not Found\r\n"

            response_header = "Server: PythonWeb1.0\r\n"
            with open("static/error.html", "rb") as _file:
                response_body = _file.read()

            response_data = (response_line + response_header + "\r\n").encode("utf-8") + response_body

            _service.send(response_data)
        else:
            response_line = "HTTP1.1 200 OK\r\n"

            response_header = "Server: PythonWeb1.0\r\n"
            response_data = (response_line + response_header + "\r\n").encode('utf-8') + response_body

            _service.send(response_data)
        finally:
            _service.close()


if __name__ == '__main__':
    server = WebServer()
    server.service_logic()

Command line startup dynamic binding port number

import socket
import threading
import sys


class WebServer(object):
    def __init__(self, addr: str = '0.0.0.0', port: int = 9091) -> None:
        self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self._server.bind((addr, port))
        print(f"Server Listen!{addr}:{port}")
        self._server.listen(128)

    def service_logic(self) -> None:
        while True:
            _services, _info = self._server.accept()
            handle_service = threading.Thread(target=self.handle_client, args=(_services, _info))
            handle_service.daemon = True
            handle_service.start()

    @staticmethod
    def handle_client(_service: socket.socket, _info: tuple) -> None:
        renv_data = _service.recv(4096)
        if len(renv_data) == 0:
            print('client', _info, 'off-line')
            _service.close()
            return

        _data = renv_data.decode('utf-8')
        url = _data.split(" ", maxsplit=2)

        uri = url[1]
        print(uri)

        if uri == "/":
            uri = '/index.html'

        try:
            with open("static" + uri, "rb") as _file:
                response_body = _file.read()
        except Exception as e:
            response_line = "HTTP/1.1 404 Not Found\r\n"

            response_header = "Server: PythonWeb1.0\r\n"
            with open("static/error.html", "rb") as _file:
                response_body = _file.read()

            response_data = (response_line + response_header + "\r\n").encode("utf-8") + response_body

            _service.send(response_data)
        else:
            response_line = "HTTP1.1 200 OK\r\n"

            response_header = "Server: PythonWeb1.0\r\n"
            response_data = (response_line + response_header + "\r\n").encode('utf-8') + response_body

            _service.send(response_data)
        finally:
            _service.close()


if __name__ == '__main__':
    args = sys.argv
    if len(sys.argv) != 2:
        print("Execute the following command: python3 xxx.py 8000")
        exit(0)

        # Determine whether all strings are composed of numbers
    if not sys.argv[1].isdigit():
        print("Execute the following command: python3 xxx.py 8000")
        exit(0)

    port = int(sys.argv[1])

    server = WebServer(port=port)
    server.service_logic()

🌟 Author related articles and resource sharing 🌟

🌟 Let the world have no technology that can't be learned 🌟
Learning C# is no longer a difficult problem
🌳 C# getting started to advanced tutorial 🌳
Relevant C# practical projects
👉 C#RS232C communication source code 👈
👉 C # entrusted data transmission 👈
👉 C# Modbus TCP source code 👈
👉 C# warehouse management system source code 👈
👉 C# Omron communication Demo 👈
👉 C#+WPF+SQL is the camera system of vehicle management station currently on-line in a city 👈
👉 2021C# and Halcon vision common framework 👈
👉 In the vision project in 2021, C# is used to complete the communication between Mitsubishi PLC and host computer 👈
👉 VP joint open source deep learning programming (WPF) 👈
✨ For C# project, please check your home page ✨
🌟 Machine vision, deep learning 🌟
Learning machine vision and deep learning are no longer difficult problems
🌌 Halcon introduction to mastery 🌌
🌌 In depth learning materials and tutorials 🌌
Machine vision, deep learning and actual combat
👉 2021 C#+HALCON vision software 👈
👉 In 2021, C#+HALCON will realize template matching 👈
👉 C# integrates Halcon's deep learning software 👈
👉 C# integrated Halcon's deep learning software with [MNIST example] data set 👈
👉 C # halcon WPF open source form control that supports equal scaling and dragging 👈
👉 Labview and HALCON in 2021 👈
👉 Labview and Visionpro in 2021 👈
👉 Automatic identification module of brake pad thickness of EMU based on Halcon and VS 👈
✨ For machine vision and in-depth learning, welcome to your personal home page ✨
🌟 Java, database tutorials and projects 🌟
Learning Java and database tutorials is no longer a difficult problem
🍏 Introduction to JAVA advanced tutorial 🍏
🍏 Getting started with database to advanced tutorial 🍏
Actual combat of Java and database projects
👉 Java classic nostalgic bully web game console source code enhanced version 👈
👉 js+css similar web version Netease music source code 👈
👉 Java property management system + applet source code 👈
👉 JavaWeb Home Electronics Mall 👈
👉 Design and implementation of JAVA hotel room reservation management system SQLserver 👈
👉 Research and development of JAVA library management system MYSQL 👈
✨ For Java, database tutorials and project practice, welcome to your personal home page ✨
🌟 Share Python knowledge, explain and share 🌟
Learning Python is no longer a difficult problem
🥝 Python knowledge and project column 🥝
🥝 "Python detects the tremble, concerns the account number tiktok". 🥝
🥝 Teach you how to install and use Python+Qt5 🥝
🥝 Q & A on the fundamentals of python Programming in 10000 words to Xiaobai 🥝
🥝 Python drawing Android CPU and memory growth curve 🥝
About Python project practice
👉 Python library management system based on Django 👈
👉 Python management system 👈
👉 Nine commonly used python crawler source codes in 2021 👈
👉 python QR code generator 👈
✨ For Python tutorial and project practice, welcome to your personal home page ✨
🌟 Share the interview questions and interview process of major companies 🌟
It's not difficult to succeed in an interview
🍏 The latest VUE interview questions of gold, nine and silver in 2021 ☀️ < ❤️ Remember to collect ❤️>>🍏
🍏 As long as you read 10000 words carefully ☀️ Linux Operating System Basics ☀️ Hang the interviewer every minute< ❤️ Remember to collect ❤️>>🍏
🍏 < ❤️ Give Xiaobai a comprehensive explanation of the basics of python Programming in 10000 words ❤️ < 😀 Remember to collect, or it will disappear 😀>>🍏
✨ About the interview questions and interview process of major companies, you are welcome to view your personal home page ✨


❤️ Pay attention to the official account of Suzhou procedures ❤️

👇 👇👇

Topics: Python Web Development network Interview