All Products
Search
Document Center

ApsaraMQ for MQTT:Sample code

Last Updated:Oct 11, 2023

This topic provides sample code on how to use the cloud SDK for .NET provided by ApsaraMQ for MQTT.

Demo

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 endpoint that is used to access ApsaraMQ for MQTT. 
        string domain = "post-cn-******-server-internet.mqtt.aliyuncs.com";  
        // The ID of the ApsaraMQ for MQTT instance. 
        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 a level-1 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);
        }
        
    }
}

Parameter description

Parameter

Description

domain

The endpoint that is used to access the ApsaraMQ for MQTT instance. You must use an endpoint to connect a client to an ApsaraMQ for MQTT broker.

If you use a cloud SDK to connect a client to ApsaraMQ for MQTT, specify the endpoint in one of the following formats:

Important

You can use a cloud SDK to connect to only ApsaraMQ for MQTT instances whose kernel version is V3.3.0 and that are deployed in regions in the Chinese mainland.

  • Public endpoint: ID of the ApsaraMQ for MQTT instance-server-internet.mqtt.aliyuncs.com

  • VPC endpoint: ID of the ApsaraMQ for MQTT instance-server-internal.mqtt.aliyuncs.com

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

instanceId

The ID of the instance that you created in the ApsaraMQ for MQTT console. You can obtain the ID of the instance in the Basic Information section of the Instance Details page in the ApsaraMQ for MQTT console.

accessKey

The AccessKey ID that you created in the Resource Access Management (RAM) console for identity authentication. For information about how to obtain an AccessKey ID, see Obtain an AccessKey pair.

Note

To prevent the leak of account information caused by hard encoding, we recommend that you obtain the AccessKey ID and AccessKey secret from the environment variables or configuration file.

secretKey

The AccessKey secret that you created in the RAM console for identity authentication. For information about how to obtain an AccessKey secret, see Obtain an AccessKey pair.

Note

To prevent the leak of account information caused by hard encoding, we recommend that you obtain the AccessKey ID and AccessKey secret from the environment variables or configuration file.

firstTopic

The topic that you created in the ApsaraMQ for MQTT console.

gid

The group that you created in the ApsaraMQ for MQTT console.

port

The port that is used by the cloud SDK for .NET. The protocol and port that are used by the cloud SDK for .NET must match. Specify the value as 5672.