Sample Code for the Cloud .NET SDK

Updated at:
Copy as MD

With the cloud .NET SDK for Message Queue for MQTT, you can send messages to a topic, subscribe to a topic, and receive client online and offline notifications. The sample code in this topic demonstrates all three capabilities in a single .NET application.

Limits

Important

Cloud SDK access is supported only for instances that run kernel version V3.3.0 or later and are deployed in the Chinese mainland.

Prerequisites

  • An instance created in the Message Queue for MQTT console.

  • A parent topic created in the Message Queue for MQTT console.

  • A group created in the Message Queue for MQTT console.

  • An AccessKey pair for your Alibaba Cloud account.

Send and receive messages

The following sample code creates one ChannelConfig object and shares it between a consumer and a producer. Three capabilities are demonstrated:

  • Message consumptionServerConsumer.SubscribeTopic subscribes to the parent topic and prints the ID of each message that is received.

  • Client status notificationsServerConsumer.SubscribeStatus subscribes to the online and offline events of the clients in a group and prints the client ID and the event type.

  • Message productionServerProducer.SendMessage publishes a message to topicA/t2 once per second and prints the ID of each message that is sent.

using System.Diagnostics.Tracing;
using System.Text;
using AliyunOnsmqttServerSdk;
using AliyunOnsmqttServerSdk.Common;
using AliyunOnsmqttServerSdk.Config;
using AliyunOnsmqttServerSdk.Model;

class Program
{
    static void Main(string[] args)
    {
        // The cloud endpoint of ApsaraMQ for MQTT.
        string domain = "post-cn-******-server-internet.mqtt.aliyuncs.com";  
        // The instance ID of ApsaraMQ for MQTT.
        string instanceId = "post-cn-******";  
        // The AccessKey ID.
        string ak = "******"; 
        // The AccessKey secret.
        string sk = "******"; 
        // The parent topic.
        string firstTopic = "topicA";
        // The group ID.
        string gid = "GID-test";
        int port = 5672;
        ChannelConfig channelConfig = new ChannelConfig(domain, instanceId, ak, sk, port);
        ServerConsumer serverConsumer = new ServerConsumer(channelConfig);
        serverConsumer.Start();
        // Subscribe to the parent topic.
        serverConsumer.SubscribeTopic(firstTopic,
            (string msgId, MessageProperties messageProperties, byte[] bArr) =>
            {
                Console.WriteLine($"recv:{msgId}");
            });
        // Subscribe to client online and offline events.
        serverConsumer.SubscribeStatus(gid,
            (statusNotice) =>{
                Console.WriteLine($"recv: {statusNotice.ClientId},{statusNotice.EventType}");
            });

        ProducerConfig producerConfig = new ProducerConfig();
        ServerProducer serverProducer = new ServerProducer(channelConfig, producerConfig);
        serverProducer.Start();
        string s = "test";
        Encoding encoding = Encoding.UTF8;
        byte[] payload = encoding.GetBytes(s);
        try
        {
            for(; ; )
            {
                Thread.Sleep(1000);
                SendResult sendResult = serverProducer.SendMessage(firstTopic+"/t2", payload);
                Console.WriteLine($"send: {sendResult.MsgId}");
            }
        }
        catch(Exception e)
        {
            Console.WriteLine(e.StackTrace);
        }

    }
}
Note

The sending loop in the sample has no exit condition. The application keeps sending one message per second until you stop it.

Parameters

ParameterDescription
domainThe endpoint of the Message Queue for MQTT instance. A client connects to the Message Queue for MQTT broker through this endpoint. For the supported formats, see Endpoints.
instanceIdThe ID of the instance. You can view the ID in the Basic Information section of the Instance Details page in the ApsaraMQ for MQTT console.
accessKeyThe AccessKey ID that you created in the Alibaba Cloud account management console. It is used for identity authentication and is assigned to the ak variable in the sample code. For instructions on how to obtain it, see Create an AccessKey pair.
secretKeyThe AccessKey secret that you created in the Alibaba Cloud account management console. It is used for identity authentication and is assigned to the sk variable in the sample code. For instructions on how to obtain it, see Create an AccessKey pair.
firstTopicThe parent topic that the sample subscribes to. The sample publishes messages to topicA/t2 under this parent topic.
gidThe ID of the group whose client online and offline events the sample subscribes to.
portThe protocol port. The port must match the protocol that is used. In the cloud SDK, this parameter is fixed to 5672.
Note

Read the AccessKey ID and AccessKey secret from environment variables or a configuration file. Hard-coding them risks leaking your Alibaba Cloud account credentials.

Endpoints

When you use the cloud SDK to connect to Message Queue for MQTT, specify the endpoint in one of the following formats:

  • Public endpoint: <instance ID>-server-internet.mqtt.aliyuncs.com

  • VPC endpoint: <instance ID>-server-internal.mqtt.aliyuncs.com

    You can view the instance ID in the Basic Information section of the Instance Details page in the ApsaraMQ for MQTT console.

The sample code in this topic uses the public endpoint format.