[Python Network Programming] Comparison of TCP and UDP

TCP transport method

1. TCP transmission characteristics

  • Connection Oriented Transport Service

    • Transmission characteristics: Provides reliable data transmission, reliability refers to no loss, no disorder, no error, no duplication during data transmission.
    • Reliability guarantee mechanism (all are automatically completed by the operating system network service for the application):
      • A data connection needs to be established before communication
      • Acknowledgment response mechanism
      • When the communication ends, the connection should be disconnected normally
  • Three-way handshake (connection establishment)

    • The client sends a message to the server requesting a connection
    • After the server receives the request, the reply message confirms that it can be connected
    • The client receives the reply and sends the final message to establish the connection

  • Four waves (disconnect)
    • The active party sends a message requesting to disconnect
    • After receiving the request, the passive party immediately responds, indicating that it is ready to disconnect
    • The passive party is ready, and sends a message again to indicate that it can be disconnected
    • The active party receives the confirmation and sends the final message to complete the disconnection

2. TCP server

  • create socket
 sockfd=socket.socket(family,type)
    Function: create socket
    Parameters: family network address type AF_INET means ipv4
         type socket type SOCK_STREAM means tcp socket (also called streaming socket)
    Return value: socket object
  • bind address (same as udp socket)

  • set monitor

 sockfd. listen(n)
    Function: Set the socket as a listening socket and determine the size of the listening queue
    Parameters: listener queue size

  • Handle client connection requests
 connfd,addr = sockfd. accept()
    Function: Block waiting to process client requests
    Return value: connfd client connection socket
            addr client address of the connection
  • messaging
 data = connfd. recv(buffersize)
    Function: accept client message
    Parameters: the size of the maximum message received each time
    Return value: received content

    n = connfd. send(data)
    Function: send message
    Parameters: the content to be sent in bytes format
    Return value: the number of bytes sent

  1. close socket (same as udp socket)

3. TCP client

  • Create a TCP socket
  • request connection
 sockfd.connect(server_addr)
    Function: connect to server
    Parameters: tuple server address

  • send and receive messages

Note: To prevent blocking at both ends, recv send should cooperate

  • close socket

4. TCP socket details

  • When one end of the tcp connection exits, if the other end is blocked in recv, recv will immediately return an empty string.

  • If one end of the tcp connection does not exist, if you still try to send data to it through send, a BrokenPipeError will occur

  • A server can connect to multiple clients at the same time, and can also be connected repeatedly

  • tcp sticky packet problem

    • cause

      • In order to solve the problem of speed inconsistency that may occur during data retransmission, the operating system sets a buffer
      • The actual network working process is more complicated, resulting in inconsistent message sending and receiving speeds
      • TCP transmits data in a byte stream, and does not distinguish message boundaries when receiving

    • the impact

      • If the content sent each time has an independent meaning, the receiving end needs to analyze it independently. At this time, the sticky packet will have an impact.
    • Approach

      • Message formatting, such as artificially adding message boundaries, used as a division between messages
      • Control the speed of sending

5. Comparison between TCP and UDP

  • transmission characteristics

    • TCP provides reliable data transmission, but UDP does not guarantee the reliability of transmission
    • TCP transmission data is processed as a byte stream, while UDP is processed as a data packet
    • TCP transmission needs to establish a connection to transmit data, and the efficiency is relatively low. UDP is relatively free, no connection is required, and the efficiency is high.
  • Socket programming difference

    • Different types of sockets created
    • The tcp socket will have sticky packets, and the udp socket will not have sticky packets if there are message boundaries
    • The tcp socket relies on listen accept to establish a connection to send and receive messages, but the udp socket does not need it
    • tcp socket uses send, recv to send and receive messages, udp socket uses sendto, recvfrom
  • scenes to be used

    • TCP is more suitable for scenarios that require high accuracy and transmit large data
      • File transfer: such as downloading movies, visiting web pages, uploading photos
      • mail sending and receiving
      • Point-to-point data transmission: such as point-to-point chat, login request, remote access, sending red envelopes
    • UDP is more suitable for scenarios where reliability requirements are not so high and transmission methods are relatively free
      • Transmission of video stream: such as live broadcast, video chat
      • Broadcasting: such as webcasting, mass messaging
      • Real-time transmission: such as game screen
    • In a large project, both TCP and UDP networks may be involved

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 top Internet companies such as Ali, Tencent, Byte, etc., and some Ali 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! !