DMS C++ API

头文件

如果是vc++编译器,还需要定义WIN32或WIN64宏
#include "dms\dms.h"

命名空间

using namespace mqtt;

初始化dms

//在连接的整个过程中,ADDRESS、CLIENTID必须都有效
const std::string ADDRESS("tcp://mqtt.dms.aodianyun.com:1883");
const std::string CLIENTID("SyncPublisher");
dms::init(ADDRESS, CLIENTID);

设置回调函数

class callback : public virtual mqtt::callback
{
public:
    virtual void connection_lost(const std::string& cause) {
        std::cout << "connection_lost" << std::endl << std::flush;
    }
    virtual void message_arrived(const std::string& topic, mqtt::message_ptr msg) {
        std::cout << topic << msg->get_payload() << std::endl << std::flush;;
    }
    virtual void delivery_complete(mqtt::idelivery_token_ptr tok) {
        std::cout << "delivery_complete" << std::endl << std::flush;
    }
};
::callback message_cb;
...
//设置回调函数
dms::set_callback(message_cb);

连接服务器

class connect_action_listener : public virtual mqtt::iaction_listener
{
    virtual void on_failure(const mqtt::itoken& tok) {
        std::cout << "connect_action_listener-->on_failure" << std::endl << std::flush;
    }
    virtual void on_success(const mqtt::itoken& tok) {
        std::cout << "connect_action_listener-->on_success" << std::endl << std::flush;
    }
};
connect_action_listener connect_listener;
...
const std::string PUB_KEY("demo");
const std::string SUB_KEY("demo");
//开始连接服务器,并等待连接完成
dms::connect(PUB_KEY, SUB_KEY, NULL, connect_listener)->wait_for_completion();
//或者不等待 dms::connect(PUB_KEY, SUB_KEY, NULL, connect_listener);

关注话题

class subscribe_action_listener : public virtual mqtt::iaction_listener
{
    virtual void on_failure(const mqtt::itoken& tok) {
        std::cout << "subscribe_action_listener-->on_failure" << std::endl << std::flush;
    }
    virtual void on_success(const mqtt::itoken& tok) {
        std::cout << "subscribe_action_listener-->on_success" << std::endl << std::flush;
    }
};
subscribe_action_listener subscribe_listener;
...
const std::string TOPIC("test");
//关注话题,并等待完成
dms::subscribe(TOPIC, NULL, subscribe_listener)->wait_for_completion();

推送消息

class publish_action_listener : public virtual mqtt::iaction_listener
{
    virtual void on_failure(const mqtt::itoken& tok) {
        std::cout << "publish_action_listener-->on_failure" << std::endl << std::flush;
    }
    virtual void on_success(const mqtt::itoken& tok) {
        std::cout << "publish_action_listener-->on_success" << std::endl << std::flush;
    }
};
publish_action_listener publish_listener;
...
const std::string TOPIC("test");
const std::string PAYLOAD("Hello World!C++");
//推送消息,并等待完成
dms::publish(TOPIC, PAYLOAD, NULL, publish_listener)->wait_for_completion();

取消关注

const std::string TOPIC("test");
//取消关注,并等待完成,或超时返回
dms::unsubscribe(TOPIC)->wait_for_completion(10000);
//也可以注册监听器

断开连接

//断开连接,并等待,或超时返回
dms::disconnect()->wait_for_completion(10000);
//也可以注册监听器

释放对象

//关闭后可以重新调用dms::init初始化
dms::close();