Todos los productos
Search
Centro de documentos

IoT Platform:Conexión de un cliente a IoT Platform mediante el SDK para .NET

Última actualización: Sep 03, 2026

Use el SDK de .NET para conectar un cliente AMQP a Alibaba Cloud IoT Platform y recibir mensajes de suscripción del lado del servidor.

Requisitos previos

Debe haber obtenido un ID de grupo de consumidores y haberse suscrito a los mensajes de tema necesarios.

Entorno de desarrollo

La tabla a continuación muestra los frameworks y las versiones compatibles.

Framework

Versión compatible

.NET Framework

3.5, 4.0, 4.5 o posterior

.NET Micro Framework

4.2 o posterior

.NET nanoFramework

1.0 o posterior

.NET Compact Framework

3.9 o posterior

.Net Core en Windows 10 y Ubuntu 14.04

1.0 o posterior

Mono

4.2.1 o posterior

Descarga del SDK

Se recomienda la biblioteca AMQP.Net Lite. Para descargarla y consultar sus instrucciones, visite AMQP.Net Lite.

Adición de la dependencia

Agregue la siguiente dependencia al archivo packages.config:

<packages>
  <package id="AMQPNetLite" version="2.2.0" targetFramework="net47" />
</packages>

Código de ejemplo

using System;
using System.Text;
using Amqp;
using Amqp.Sasl;
using Amqp.Framing;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Security.Cryptography;
namespace amqp
{
    class MainClass
    {
        // The endpoint. For more information, see Connect an AMQP client to IoT Platform.
        static string Host = "${YourHost}";
        static int Port = 5671;
        // Hardcoding the AccessKey ID and AccessKey Secret in your code poses security risks. We recommend using environment variables to store your credentials. This example demonstrates how to retrieve the AccessKey ID and AccessKey Secret from environment variables.
        static string AccessKey = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
        static string AccessSecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        static string consumerGroupId = "${YourConsumerGroupId}";
        static string clientId = "${YourClientId}";
        // The ID of the instance.
        static string iotInstanceId = "${YourIotInstanceId}"; 
        static int Count = 0;
        static int IntervalTime = 10000;
        static Address address;
        public static void Main(string[] args)
        {
            long timestamp = GetCurrentMilliseconds();
            string param = "authId=" + AccessKey + "&timestamp=" + timestamp;
            // For information about how to construct the userName parameter, see Connect an AMQP client to IoT Platform.
            string userName = clientId + "|authMode=aksign,signMethod=hmacmd5,consumerGroupId=" + consumerGroupId
               + ",iotInstanceId=" + iotInstanceId + ",authId=" + AccessKey + ",timestamp=" + timestamp + "|";
            // Calculate the signature. For information about how to construct the password, see Connect an AMQP client to IoT Platform.
            string password = doSign(param, AccessSecret, "HmacMD5");
            DoConnectAmqp(userName, password);
            ManualResetEvent resetEvent = new ManualResetEvent(false);
            resetEvent.WaitOne();
        }
        static void DoConnectAmqp(string userName, string password)
        {
            address = new Address(Host, Port, userName, password);
            // Create a connection.
            ConnectionFactory cf = new ConnectionFactory();
            // Optional: Use a local TLS certificate.
            //cf.SSL.ClientCertificates.Add(GetCert());
            //cf.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
            cf.SASL.Profile = SaslProfile.External;
            cf.AMQP.IdleTimeout = 120000;
            // Customize the cf.AMQP.ContainerId and cf.AMQP.HostName parameters.
            cf.AMQP.ContainerId = "client.1.2"; 
            cf.AMQP.HostName = "contoso.com";
            cf.AMQP.MaxFrameSize = 8 * 1024;
            var connection = cf.CreateAsync(address).Result;
            // Register a callback to handle connection closure.
            connection.AddClosedCallback(ConnClosed);
            // Receive messages.
            DoReceive(connection);
        }
        static void DoReceive(Connection connection)
        {
            // Create a session.
            var session = new Session(connection);
            // Create a receiver link to receive messages.
            var receiver = new ReceiverLink(session, "queueName", null);
            receiver.Start(20, (link, message) =>
            {
                object messageId = message.ApplicationProperties["messageId"];
                object topic = message.ApplicationProperties["topic"];
                string body = Encoding.UTF8.GetString((Byte[])message.Body);
                // Note: Avoid long-running tasks in this callback. If you need to perform business logic, run it in a separate thread. This prevents the consumer from being blocked, which can lead to message redelivery.
                Console.WriteLine("receive message, topic=" + topic + ", messageId=" + messageId + ", body=" + body);
                // Acknowledge the message.
                link.Accept(message);
            });
        }
        // If a connection error occurs, the client attempts to reconnect.
        // This is a simple retry example. For production environments, consider implementing a more robust reconnection strategy, such as exponential backoff.
        static void ConnClosed(IAmqpObject _, Error e)
        {
            Console.WriteLine("An error occurred: " + e);
            if(Count < 3)
            {
                Count += 1;
                Thread.Sleep(IntervalTime * Count);
            }
            else
            {
                Thread.Sleep(120000);
            }
            // Reconnect.
            DoConnectAmqp(address.User, address.Password);
        }
        static X509Certificate GetCert()
        {
            string certPath = Environment.CurrentDirectory + "/root.crt";
            X509Certificate crt = new X509Certificate(certPath);
            return crt;
        }
        static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        static long GetCurrentMilliseconds()
        {
            DateTime dt1970 = new DateTime(1970, 1, 1);
            DateTime current = DateTime.Now;
            return (long)(current - dt1970).TotalMilliseconds;
        }
        // Signature method. Supported algorithms: hmacmd5, hmacsha1, and hmacsha256.
        static string doSign(string param, string accessSecret, string signMethod)
        {
            //signMethod = HmacMD5
            byte[] key = Encoding.UTF8.GetBytes(accessSecret);
            byte[] signContent = Encoding.UTF8.GetBytes(param);
            var hmac = new HMACMD5(key);
            byte[] hashBytes = hmac.ComputeHash(signContent);
            return Convert.ToBase64String(hashBytes);
        }
    }
}

Configure los parámetros del código anterior como se describe en la tabla a continuación. Para obtener más información, consulte Connect an AMQP client to IoT Platform.

Importante

Especifique valores de parámetro válidos. De lo contrario, el cliente AMQP no podrá conectarse a IoT Platform.

Parámetro

Descripción

Host

Endpoint de conexión AMQP.

Para obtener más información sobre el endpoint que puede especificar en la variable ${YourHost}, consulte Manage the endpoint of an instance.

AccessKey

Inicie sesión en la consola de IoT Platform, pase el cursor sobre el icono de perfil en la esquina superior derecha y haga clic en AccessKey Management para obtener el AccessKey ID y el AccessKey secret.

Nota

Si usa un usuario RAM, debe adjuntar la directiva AliyunIOTFullAccess al usuario RAM para otorgarle permisos de gestión de recursos de IoT Platform. De lo contrario, la conexión será con errores. Para obtener más información, consulte Access IoT Platform as a RAM user.

AccessSecret

consumerGroupId

ID del grupo de consumidores en la instancia de IoT Platform.

Inicie sesión en la consola de IoT Platform. En la instancia correspondiente, vaya a Message Forwarding > Server-side Subscription > Consumer Group List para consultar su ID de grupo de consumidores.

iotInstanceId

ID de la instancia. Puede encontrar este valor en la pestaña Overview de la consola de IoT Platform.

  • Si se muestra un ID de instancia, establezca este parámetro con dicho ID.

  • Si la pestaña Overview no se muestra o su instancia no tiene ID, deje este parámetro vacío con el formato iotInstanceId = "".

clientId

ID del cliente. Debe definir este ID, el cual puede tener hasta 64 caracteres. Se recomienda usar un identificador único, como el UUID, la dirección MAC o la dirección IP del servidor donde se encuentra su cliente AMQP.

Una vez que el cliente AMQP esté conectado e iniciado, inicie sesión en la consola de IoT Platform. En la página Message Forwarding > > > Server-side Subscription de la instancia, dentro de la pestaña Consumer Groups, haga clic en View junto al grupo de consumidores. La página Consumer Group Details muestra este parámetro para ayudarle a identificar los distintos clientes.

Resultados de ejemplo

  • Éxito: La salida a continuación indica que la conexión se estableció correctamente y que se recibieron mensajes.

    receive message, topic=/xxx/xxx/thing/event/property/post, messageId=xxx, body={"deviceType":"xxx","iotId":"xxx","requestId":"xxx","checkFailedData":{},"productKey":"xxx"}
    receive message, topic=/xxx/xxx/thing/event/property/post, messageId=xxx, body={"deviceType":"xxx","iotId":"xxx","requestId":"xxx","checkFailedData":{},"productKey":"xxx"}
    receive message, topic=/xxx/xxx/thing/event/property/post, messageId=xxx, body={"deviceType":"xxx","iotId":"xxx","requestId":"xxx","checkFailedData":{},"productKey":"xxx"}

    Parámetro

    Ejemplo

    Descripción

    topic

    //*/thing/event/property/post

    Tema para enviar propiedades del dispositivo.

    messageId

    2****7

    ID del mensaje.

    body

    {"deviceType":"CustomCategory","iotId":"4EwuVV","requestId":"161268","checkFailedData":{},"productKey":"g4***S","gmtCreate":1612682173249,"deviceName":"Esensor","items":{"temperature":{"value":-1,"time":1612682173247},"humidity":{"value":74,"time":1612682173247}}}

    Cuerpo del mensaje.

  • Error: La salida a continuación indica que la conexión fue con errores.

    Thread xxx has exited with code 0 (0x0).
    Exception thrown: xxx (in xxx L)
    An unhandled exception of type 'Sys xxx n' occurred in m xxx 11
    One or more errors occurred.

Referencias

Para obtener más información sobre los códigos de error de los mensajes de suscripción del lado del servidor, consulte Message-related error codes.