Simple, fun and easy to understand! Python UDP network programming

1. What is UDP?

UDP stands for the User Datagram Protocol , Chinese is the User Datagram Protocol . It is a connectionless transport layer protocol in the Internet protocol set , providing simple and unreliable transaction-oriented transmission services. To put it simply, UDP is a transport protocol at the transport layer . There is no need to establish a connection with the target host during transmission . You can directly transmit as long as you know the other party's ip and port number . We can compare UDP to writing a letter : you need to write the mailing address and mailing number every time you send a letter. You can send it directly without calling the other party before sending it.
We have a general understanding of the definition of UDP, so let's take a look at the characteristics of the "write letter mode".

Second, the characteristics of UDP

1. Unreliability:

UDP does its best to deliver, but it does not guarantee delivery . In other words, the integrity and reachability of data transmitted through the UDP protocol cannot be guaranteed . The host will not be notified whether it arrives or does not arrive . Therefore, there is no need to maintain the complicated connection relationship between the host and the target host. In layman’s terms, it’s like ancient times. You have to share a book with your girlfriend in a different place (e.g. long-distance relationship in ancient times...). You just send the envelope, and you don’t know whether the pigeon encountered it on the way. What's wrong, can the envelope be conveyed (in case of encountering Lord Bei, then cake...)

Since UDP is unreliable, is there no need for UDP to exist? The answer is no . UDP is not bundled with a large number of security functions like tcp, so UDP will not have a lot of system overhead during the transmission process, which greatly reduces the execution time , thereby improving the transmission efficiency . This efficiency is tcp It's hard to remember. Due to the advantages of UDP transmission speed, UDP is very important for some real-time applications.

 2. No connectivity:

UDP is connectionless , that is, there is no need to establish a connection before communication , and the transport layer of the target host does not give a confirmation after receiving it . Following the previous analogy, you don't need to notify your girlfriend when you let the pigeon fly (it seems that there is no way to notify...); even if the pigeon delivers the envelope, she cannot immediately notify you "I have received it."

3. Message-oriented:

Application layer packets passed down the network layer and handed to the ip packets are not altered , directly add / remove header for the next step. If the message is too long, it will be fragmented at the ip layer ; if the message is too short, the header of the datagram at the ip layer will be very long. I don’t use Fei Ge Chuan Shu here anymore, use the upgraded version of Fei Ge Chuan Shu-write letter (emmm...passed through): When you write a letter, put the letter (data field) in the envelope (first part) When the content is too much, several pieces of letter paper will be used; when the content is too small, the number of words may not be as large as that on the envelope. And when your girlfriend receives the letter, just open the envelope and you can read your "little love letter".

4. No congestion mechanism:

The transmission rate of the source host will not be reduced after network congestion , which is very important for some real-time applications. Such as IP phone, real-time video, etc. At the same time allowed when the network is congested lose some data , but it does not allow data much delay .

Because UDP does not have a congestion mechanism, when too many source hosts send high-rate real-time data to the network at the same time, it is likely to cause congestion and result in data loss. For some real-time applications, this unreliable transmission can be appropriately improved, and some protection and repair measures can be added, such as forward error correction or retransmission of lost packets .

5. There is no clear sense of client and server

You can both write and receive letters, there is not much difference between the two (love is originally mutual...).

6. Support one-to-one, one-to-many, many-to-one, many-to-many interactive communication

  • Unicast: Unicast is a one-to-one communication mode. The sender needs to specify the other party's ip and port, and only the corresponding machine can receive the sent data, and it will not have any impact on other machines in the subnet.
  • Multicast : Multicast is a one-to-many communication mode. One machine communicates with part of all machines in the subnet. These machines can all receive the data sent by the host, but the unspecified machines in the subnet are not affected.
  • Broadcast : When the number of machines in the multicast is the number of all machines in the subnet, the "multicast" at this time is no longer called multicast, but broadcast. It is stipulated in the ip protocol that broadcasting can only be carried out in a subnet, but not in a wide area network.
  • Multicast : Similarly, multicast is also a one-to-many communication mode. After a machine joins a multicast ip and then sends data to the multicast ip, all the machines in the multicast can receive the data.

 

7. The header overhead is small, only 8 bytes

UDP consists of two parts , one is the header field , and the other is the data field .
The header field has only 8 bytes and is divided into 4 fields :

  • Source port : Source port number. Choose when you need the other party to reply, and use all 0 when you don’t need it.
  • Destination port : Destination port number. Used at the end of delivery.
  • Length : The length of the udp user datagram, the minimum value is 8 (only the header).
  • Checksum : Check whether there is any error in the transmission of the udp user datagram, and discard it if there is an error.

Three, socket communication

In fact, the way to create a socket is similar to the way to read and write files. Do you still remember how to read and write files? Let us recall together:

f  = open()   # 打开文件
f.read()/f.write()    #  对文件进行操作
f.close()   # 关闭文件   

Let's look at the way to create a socket again:

1. Import the socket module

import socket

2. Create a socket object (socket)

t = socket.socket(socket.AF_INET,sockeet.SOCK_DGRAM)

When creating a socket, socket requires two parameters socket (AddressFamily, Type)

AdressFamily : You can choose AF_INET (for communication between Internet processes) or AF_UNIX ( for communication between processes on the same machine), AF_INET is commonly used in practice.
Type : It can be SOCK_STREAM (stream socket, mainly used for TCP protocol) or SOCK_DGRAM (Datagram socket, mainly using UDP protocol).

3. Bind local information (bind)

t.bind(("",5678))   #参数为一个含有两位元素的元组,第一个元素为本机ip,默认自动分配;第二个元素为端口号。

4. Use socket to receive/send data (recvfrom/sendto)

# 1.发送数据
data = ""   # 需要发送的数据
t.sendto(data.encode("转码"),("ip",port))   # 两个参数:参数1为传输数据,参数2为元组("目标ip",目标端口)

# 2.接收数据
recv _data, dest_ip_and_port = t.recvfrom(1024)   # 返回数据:数据内容,对方的(ip和端口号)

Close the socket (close)

t.close()  

Follow me and have fun with python!

 

Guess you like

Origin blog.csdn.net/qq_45807032/article/details/105139292
Recommended