阅读量:2
import socket
# 创建UDP socket
udp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定地址和端口
server_address = ('localhost', 12000)
udp_server_socket.bind(server_address)
# 服务器循环
while True:
# 接收客户端消息
message, client_address = udp_server_socket.recvfrom(1024)
print(f"Received message: {message} from {client_address}")
# 处理消息(这里仅回显相同的消息)
udp_server_socket.sendto(message, client_address)
# 关闭socket
udp_server_socket.close()