M2MQTT 使用方式

导入文件

M2MqttEx.dll

命名空间

using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

初始化

//DMS.Init() //默认地址也是mqtt.dms.aodianyun.com
DMS.Init("mqtt.dms.aodianyun.com");

注册事件

/* 调用事件是在单独的线程中进行的 */
//当推送消息成功后,该事件会被调用
DMS.MqttMsgPublished += MqttMsgPublished;
//当连接断开后,该事件会被调用
DMS.ConnectionClosed += ConnectionClosed;
//关注话题成功后,该事件会被调用
DMS.MqttMsgSubscribed += MqttMsgSubscribed;
//取消关注成功后,该事件会被调用
DMS.MqttMsgUnsubscribed += MqttMsgUnsubscribed;
//当接收到关注的消息后,该事件会被调用
DMS.MqttMsgPublishReceived += MqttMsgPublishReceived;

事件定义

static void MqttMsgPublished(object sender, MqttMsgPublishedEventArgs e)
{
    //do something ...
     Console.WriteLine("MqttMsgPublished");
}
static void ConnectionClosed(object sender, EventArgs e) 
{
    Console.WriteLine("-->ConnectionClosed");
}
static void MqttMsgSubscribed(object sender, MqttMsgSubscribedEventArgs e)
{
    Console.WriteLine("MqttMsgSubscribed");
}
static void MqttMsgUnsubscribed(object sender, MqttMsgUnsubscribedEventArgs e)
{
    Console.WriteLine("MqttMsgUnsubscribed");
}
static void MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
    //打印接收到的消息
    Console.WriteLine("MqttMsgPublishReceived:" + Encoding.UTF8.GetString(e.Message));
}

连接服务器

const string pub_key = "demo";
const string sub_key = "demo";
DMS.Connect(clientId, pub_key, sub_key);

关注话题

const string topic = "test";
//关注成功后,DMS.MqttMsgSubscribed事件会被调用
DMS.Subscribe(topic);

推送消息

const string topic = "test";
const string message = "hello Word";
//推送消息成功后,DMS.MqttMsgPublished事件会被调用
DMS.Publish(topic,message);

取消关注话题

const string topic = "test";
//取消成功后,DMS.MqttMsgUnsubscribed事件会被调用
DMS.Unsubscribe(topic);

断开连接

//断开连接后,DMS.ConnectionClosed事件会被调用
DMS.Disconnect();
展开阅读全文

没有更多推荐了,返回首页