Python uses sockets to implement UDP sending and receiving data
To implement sending and receiving data through UDP using Python, the following preparations need to be made:
1. Install Python and corresponding development environment: Ensure that Python is already installed on the computer and the socket class library is installed.
2. Open Python development environment: use any Python Integrated development environment (IDE) or text editor to open a new Python file.
The following are the class libraries that need to be relied on in Python:
1. Socket Class Library: Python's socket class library provides support for socket programming, allowing us to use the UDP protocol for network communication.
Now, let's start implementing examples of sending and receiving data through UDP, and provide the complete Python code:
python
import socket
#Creating UDP sockets
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#Set the target host and port number
target_host = "localhost"
target_port = 1234
#Sending data
message = "Hello, UDP server!"
udp_socket.sendto(message.encode(), (target_host, target_port))
#Receiving data
data, addr = udp_socket.recvfrom(1024)
print("Received:", data.decode())
#Close socket
udp_socket.close()
In the above code, we first imported the socket module. Then, we created a UDP socket instance, specifying the use of IPv4 and UDP protocol (SOCK_DGRAM). Next, we set the target host and port number, and then sent a message. We send data by calling the 'sendto()' function, where the first parameter is the data to be sent and the second parameter is a tuple of the target host and port number.
Next, we use the 'recvfrom()' function to receive data. It returns the received data and the address of the sent data (a tuple of host and port numbers). We can use the 'decode()' function to convert the received data from bytes to a string and print it out.
Finally, we close the socket.
Summary:
Through Python's socket library, we can easily achieve sending and receiving data through UDP. To use UDP for network communication, you need to create a UDP socket, set the target host and port number, and then use the 'sendto()' function to send data, and use the 'recvfrom()' function to receive data. Finally, remember to close the socket.