Dealing with the application layer: UDP socket programming

UDP

UDP is a lightweight transport protocol that does not provide unnecessary services, it only provides minimal services. UDP is connectionless , so there is no handshake process before the two processes communicate . The UDP protocol provides an unreliable data transmission service. That is to say, when a process sends a message into a UDP socket, the UDP protocol does not guarantee that the message will reach the receiving process. Not only that, the packets that arrive at the receiving process may also arrive out of order.
UDP does not include a congestion control mechanism, so the sender of UDP can inject data into its lower layer (network layer) at any rate it chooses. (However, it is worth noting that the actual end-to-end throughput may be less than this rate, which may be due to the limited bandwidth of the intermediate link or due to congestion.)-"Computer Networking A Top-down Approach"

  • Please think: UDP compared to TCP, there are many services not provided, so why do you need UDP?
    Simply put, since UDP does not require a handshake and no flow control, it can be transmitted quickly, which can reflect higher efficiency in some scenarios. At the same time, because UDP is unreliable, there is no need for retransmission, and there is no problem of out-of-sync for Internet telephony.

Socket programming (UDP)

For a network application, how do they interact with each other? For a typical network application, two programs need to be completed together, namely the client program and the server program , which will be located in the two end systems. When I run these two programs, a client process and a server process will be created, and these two processes will communicate between the end systems through the reading and writing of sockets.

Theoretical basis

Now our idea is to program a pair of applications- client application programmer and server application . In this blog we chose to run on UDP, the principle is to send independent data from one end system to another end system Packets, because UDP is connectionless, no guarantee is provided for the content of the interaction when sending packets.
Through learning, we know that the processes of different end systems send messages to the socket between each other. Through such information interaction to achieve communication, the socket is like access control. To communicate with the application, you need to first Through the access control verification, my guests are allowed to enter. In the same way, no message can go out at will, and only allowed messages will be sent out!

First of all, we must first add the destination address to a group. This is equivalent to the permission of the group, then we can start through the "access" of the socket. After departure, everything will be handed over to the Internet. The Internet will send the packet to the socket of the receiving process through a series of operations. When the receiving socket receives the packet, the process will retrieve the packet through the socket and exchange information.
This process can be imagined as sending a letter. You need to complete the information that a letter should have, such as postal code, stamp, recipient information, etc., and then give it to the postman. The postman will use his Ways to get the letter to the recipient's door. The recipient didn't accept the letter when he saw it, but first looked at whether the letter was for himself, and then took it into the door.

So the question we are more concerned about is, what kind of information do we need to group into order to achieve such a function? In order to connect to the host, we need the IP address of the target host , so that we can know which end system to send to. If you want to send a message, there must be a recipient. Sending a letter without a recipient is a meaningless thing. But since there may be multiple processes running on a host, which process should I send to? Surely you can't send it randomly, so we need to specify a port number, So that the designated process can receive packets from the designated place. It should be emphasized that the ports we write need to avoid the RFC- defined protocol, such as the HTTP protocol port number 80, because if we send packets from these ports, we will "string", which is something we do n’t want to see. .

greet! (Program requirements)

Let's make a basic thing, let the client and server greet each other!

  1. The prompt message is displayed, and the customer enters his name from the keyboard;
  2. Send the data to the server through the program;
  3. The server receives the data and generates a greeting message, such as "Hello!";
  4. The server sends the data back to the client;
  5. The customer receives the data and displays the returned data.
  • The following is implemented in Python.

UDPClient

We go step by step, "A clever woman can't cook without rice ". First of all, I need some tools to make sockets, so we don't need to make wheels. There is a module in Python dedicated to this task, called " socket " We will include it first.

from socket import *

Next, I need to explain the destination host of the received packet, and then create 2 variables to store it.

Name = '名字'    #用字符串来存目的地址,“名字”需要替换为目的地的 IP 地址或域名 
Port = 端口号    #“端口号”需要替换为一个存在的端口,例如 12000,注意不要“串线”

Well, next we need to generate a socket to work, let's just look at the code. But now we may be confused by this code, what is this? Don't worry, we will know "AF_INET" and "SOCK_DGRAM" when we learn the network layer. Simply put, this code creates a UDP type socket, we just write it down first.

Socket = socket(AF_INET,SOCK_DGRAM)

Next we will ask the customer to enter his name as the request says. The interactivity of the software is better, we can also come to prompt information.

print("现在向服务器打个招呼吧!")
message = input("Nice to meet you! My name is ")

Well, now that we have both sockets and packets , we will send the information out next. First of all, we must first convert the message to a byte type. Here we can call the " .encode () " method to complete, and then we let this message carry the destination address and port number. The packet can be sent to the socket
through the " .sendto () " method. The next operation is done automatically by the socket internally, we don't need to worry too much.

Socket.sendto(message.encode(),(Name,Port))

So far, we have completed the need to send packets. But it is not over yet, we have to accept the information returned by the server, and do some responses to indicate that we have successfully accepted.
Look at the following statement, using " Socket.recvfrom () " can make the socket accept the returned information, and then we assign this information to two variables to store the returned packet and the address of the server (in fact, this thing we temporarily Not needed). What does "2048" mean? It means that the ".recvfrom ()" method uses a buffer length of 2048 as input, and it doesn't matter if you don't understand.

backdMessage,address = Socket.recvfrom(2048)

Then we take a look at the group output.

print(backMessage.decode())

Remember when we read the file, what do we do after the operation? That is to close the file, which is a good habit. The same is true for sockets, we also need to develop good habits, close a process after it is used up. The ".close ()" method can achieve this function. At this point, the programming is over!

Socket.close()

UDPServer

We just wrote a client-side Python program, now let's write a server-side program. Step by step, first of all, let's first include the " Socket " module.

from socket import *

Next, we need to specify the port number, which means that the socket of my server only accepts the information from a certain port, reflecting a " door to door "! We use a variable to store the port number, and then we have to create a socket as above, we bind the port number to this socket through the ".bind ()" method.

Port = 端口号    #“端口号”需要替换为一个存在的端口,例如 12000,注意不要“串线”
Socket = socket(AF_INET,SOCK_DGRAM)
Socket.bind(('',Port))

With the above code, the server's socket can receive information from the specified port number. In order to indicate the smooth implementation of the above operation, we output a prompt message.

print("准备就绪,可以接收分组!")

As a server, we must not only receive the packet once, but we must be constantly preparing the corresponding packets. That is to say, my server must continue to be in working condition. We use an endless loop " while true " to realize that this time the endless loop will not consume too much resources, because after the next statement reads the group, it will take action.
If a packet is received, the " .recvfrom () " method will start working, storing the data and the sender's address. Here, because we are going to send packets back, the sender address here is very important. When we edit the reply message, we must submit the sender's address to the socket through the " .sendto () " method. word. Then don't worry about it, let the socket complete!

while True:
    message,Address = Socket.recvfrom(2048)
    backMessage = "Hello, " + message.decode().upper()+"! My name is Han Meimei!"
    Socket.sendto(backMessage.encode(),Address)

Of course, some friends will ask, when will this endless loop stop? It's so simple, just close the program when you don't want to use it!

Program test

Since I do n’t have any friends to accompany me, I had to do a test on one machine and start the server program “UDPServer.py” first.

Seeing the prompt message proves that the server started very successfully, then start the client program.

It looks pretty smooth, let's say hello!

The program fulfilled our needs!

References

"Computer Networks" edited by Xie Xiren, Electronic Industry Press
"Computer Networks Top-Down Method" [US] James F. Kurose Keith W. Ross, translated by Chen Ming,
why many network protocols of Machinery Industry Press are mainly UDP What about
the difference between tcp and upd? Why use udp and
why is there a UDP protocol?

Guess you like

Origin www.cnblogs.com/linfangnan/p/12694936.html