import socket # --- Configuración del Destino --- # IP (localhost) y Puerto del servidor/receptor UDP IP_DESTINO = "127.0.0.1" PUERTO_DESTINO = 6543 DIRECCION_DESTINO = (IP_DESTINO, PUERTO_DESTINO) # Mensaje a enviar MENSAJE = "Hola Mundo UDP" # 1. Crear el socket UDP # socket.AF_INET: Familia de direcciones IPv4 # socket.SOCK_DGRAM: Indica el uso de datagramas (protocolo UDP) try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as cliente_socket: # 2. Codificar el mensaje # Los sockets solo pueden enviar bytes, por lo que la cadena (string) debe codificarse. datos_a_enviar = MENSAJE.encode('utf-8') # 3. Enviar los datos # sendto() envía los datos al destino especificado. cliente_socket.sendto(datos_a_enviar, DIRECCION_DESTINO) print(f"Mensaje enviado con éxito: '{MENSAJE}'") print(f"Destino: {IP_DESTINO}:{PUERTO_DESTINO} (UDP)") except Exception as e: print(f"Ocurrió un error al intentar enviar el mensaje: {e}")