推荐答案
// www.javascriptcn.com code example
import socket
# 创建 UDP 套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定本地地址和端口
udp_socket.bind(('localhost', 12345))
# 发送数据
udp_socket.sendto(b'Hello, UDP!', ('localhost', 12346))
# 接收数据
data, addr = udp_socket.recvfrom(1024)
print(f"Received message: {data.decode()} from {addr}")
# 关闭套接字
udp_socket.close()本题详细解读
1. 创建 UDP 套接字
在 Python 中,使用 socket.socket() 函数创建套接字。对于 UDP 通信,需要指定 socket.AF_INET 表示使用 IPv4 地址族,socket.SOCK_DGRAM 表示使用数据报套接字(UDP)。
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2. 绑定本地地址和端口
使用 bind() 方法将套接字绑定到本地地址和端口。这一步是可选的,通常用于接收数据的服务器端。
udp_socket.bind(('localhost', 12345))3. 发送数据
使用 sendto() 方法发送数据。该方法需要传入要发送的数据和目标地址(IP 地址和端口)。
udp_socket.sendto(b'Hello, UDP!', ('localhost', 12346))4. 接收数据
使用 recvfrom() 方法接收数据。该方法返回接收到的数据和发送方的地址。
data, addr = udp_socket.recvfrom(1024)
print(f"Received message: {data.decode()} from {addr}")5. 关闭套接字
使用 close() 方法关闭套接字,释放资源。
udp_socket.close()
6. 注意事项
- UDP 是无连接的协议,因此不需要像 TCP 那样建立连接。
sendto()和recvfrom()是 UDP 通信的核心方法。- 由于 UDP 是不可靠的协议,数据可能会丢失或乱序,因此在实际应用中可能需要额外的机制来确保数据的可靠性。