[python network programming] the difference between TCP and UDP

TCP (Transmission Control Protocol), referred to as Transmission Control Protocol, is a connection-oriented, reliable, byte-stream-based transport layer communication protocol.

Three steps to create TCP communication:

  1. create connection
  2. data transmission
  3. terminate connection

TCP communication is similar to making a phone call in life, and the relevant connection must be established before the communication starts.

TCP Features:

  1. Connection-oriented This connection is one-to-one, so TCP is not suitable for broadcast applications
  2. Reliable Transmission
    1. TCP uses an acknowledgment mechanism
    2. timeout retransmission
    3. error checking
    4. Flow Control and Congestion Management

TCP advantages:

  • reliable and stable
  • Suitable for transferring large amounts of data

TCP Disadvantages:

  • slow transfer
  • High system resource usage

TCP usage scenarios

Higher requirements for network communication quality

  • Browser HTTP protocol based on TCP protocol
  • file transfer

TCP three-way handshake (connection)

TCP’s 4 waves (disconnect)

TCP network program flow

Case file downloader based on TCP (synchronous download)

TCP strictly distinguishes between client and server.

TCP client

import socket

if __name__ == '__main__':
    # create tcp client socket
    tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Establish a connection with the server program
    tcp_client_socket.connect(("127.0.0.1", 8989))
    # Receive the file name data downloaded by the user
    file_name = input("Please enter the file name you want to download:")
    # Encode string process into binary data
    file_name_data = file_name. encode("utf-8")
    # send data
    tcp_client_socket.send(file_name_data)

    # Specify the path, first create the file to the specified path, and then write data in the open file
    with open("/home/python/Desktop/" + file_name, "wb") as file:

        # Loop to receive the file binary data sent by the server
        while True:
            # Receive data sent by the server once
            file_data = tcp_client_socket.recv(1024)
            if file_data:
                # Loop to write data to the file
                file. write(file_data)
            else:
                # The server sends the file to complete
                break

    # close the socket
    tcp_client_socket. close()

TCP server

import socket
import os


if __name__ == '__main__':
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Set the socket option, the port number will be released immediately when the program exits, and the port number can be reused
    # Tip: The default is tcp disconnection, but it takes 1-2 minutes to actually release the port number
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,True)
    # Bind the port number to the program
    tcp_server_socket. bind(("", 8989))
    # Set up monitoring
    tcp_server_socket.listen(128)
    # Waiting for the connection request from the client in a loop, it can serve multiple clients, but only after one client downloads the file can the other client download the file
    while True:
        # Waiting to receive connection requests from clients
        service_client_socket, ip_port = tcp_server_socket. accept()
        # The code is executed here, indicating that the connection is established successfully
        print("Client ip address and port number:", ip_port)
        # Receive client request data (actually the file name sent by the client)
        recv_data = service_client_socket. recv(1024)
        # Decode binary data
        file_name = recv_data. decode("utf-8")
        print(file_name)

        # Check if the requested file exists
        # 1. try-except If an exception occurs when opening the file, it means the file does not exist
        # 2. os.path.exits to determine whether the file exists
        # Determine whether the specified file or folder exists
        if os.path.exists(file_name):
            # Open the specified file according to the file name requested by the client, and read the data in the file
            with open(file_name, "rb") as file:
                while True:
                    # read file data
                    file_data = file. read(1024)
                    if file_data:
                        # send data to client
                        service_client_socket. send(file_data)
                    else:
                        # file read complete
                        break
        else:
            service_client_socket.send("No such file".encode("utf-8")
        service_client_socket. close()
    #tcp_server_socket.close()

TCP note:

  1. Generally, the tcp server needs to bind the port number, otherwise the client cannot find the server
  2. The tcp client generally does not bind the port number, just use a randomly generated port number
  3. When a tcp client is successfully connected to the server, there will be a new socket on the server side, which is used to mark the client and serve the client alone
  4. The socket after listen is a passive socket, which is only used to receive the connection request of the new client, and the new socket returned by accept marks the new client
  5. Closing the socket after listening means that the passive socket is closed, which will cause the new client to be unable to connect to the server, but the previously connected client can communicate normally
  6. Closing the socket returned by accept means that the client has been served, pay attention to the difference from point 5
  7. When the client’s socket calls close, the server will recv unblock it, and the length returned is 0, so the server can distinguish whether the client has gone offline by the length of the returned data

The difference between TCP and UDP

  1. TCP is connection-oriented, UDP is not connection-oriented
  2. TCP needs to connect and the transmission speed is slow, UDP does not need to connect and the transmission speed is fast
  3. TCP does not support broadcasting, UDP supports broadcasting
  4. TCP has more requirements on system resources, and UDP has less requirements on system resources.
  5. TCP provides reliable data transmission, while UDP does not guarantee reliable data transmission and is prone to packet loss
  6. TCP is suitable for sending large amounts of data, UDP is suitable for sending small amounts of data
  7. TCP has flow control, UDP has no flow control

If you are interested in Python, you can try this complete set of Python learning materials I compiled, and get it for free at the end of the article

Including: Python permanent use installation package, Python web development, Python crawler, Python data analysis, artificial intelligence, machine learning and other learning tutorials. Take you to learn Python systematically from zero foundation!

Introduction to zero-based Python learning resources

1. Learning routes in all directions of Python

The route of all directions in Python is to organize the commonly used technical points of Python to form a summary of knowledge points in various fields. Its usefulness lies in that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.

2. Python learning software

If a worker wants to do a good job, he must first sharpen his tools. The commonly used development software for learning Python is here!

3. Python introductory learning video

There are also many learning videos suitable for getting started with 0 basics. With these videos, you can easily get started with Python~

4. Python exercises

After each video lesson, there are corresponding practice questions, you can test the learning results haha!

5. Python actual combat case

Optical theory is useless. You have to learn to type codes along with it, and then you can apply what you have learned in practice. At this time, you can learn from some practical cases. This information is also included~

6. Python interview materials

After we have learned Python, we can go out and find a job with the skills! The following interview questions are all from first-line Internet companies such as Alibaba, Tencent, and Byte, and some Alibaba bosses have given authoritative answers. After reading this set of interview materials, I believe everyone can find a satisfactory job.

7. Data collection

The above-mentioned full version of the full set of learning materials for Python has been uploaded to the CSDN official website. Those who need it can scan the QR code of the CSDN official certification below on WeChat and enter the “receive materials” to get it for free! !