mosquitto c++ example 发布消息
使用mosquitto c++ 实现publish发布消息到broker
file mymosq.h
class myMosq : public mosqpp::mosquittopp
{
private:
const char * host;
const char * id;
const char * topic;
int port;
int keepalive;
void on_connect(int rc);
void on_disconnect(int rc);
void on_publish(int mid);
public:
myMosq(const char *id, const char * _topic, const char *host, int port);
~myMosq();
bool send_message(const char * _message);
};
file mymosq.cpp
#include "mymosq.h"
#include <iostream>
myMosq::myMosq(const char * _id,const char * _topic, const char * _host, int _port) : mosquittopp(_id)
{
mosqpp::lib_init();
this->keepalive = 60;
this->id = _id;
this->port = _port;
this->host = _host;
this->topic = _topic;
connect_async(host,
port,
keepalive);
loop_start();
};
myMosq::~myMosq() {
loop_stop();
mosqpp::lib_cleanup();
}
bool myMosq::send_message(const char * _message)
{
int ret = publish(NULL,this->topic,strlen(_message),_message,1,false);
return ( ret == MOSQ_ERR_SUCCESS );
}
void myMosq::on_disconnect(int rc) {
std::cout << ">> myMosq - disconnection(" << rc << ")" << std::endl;
}
void myMosq::on_connect(int rc)
{
if ( rc == 0 ) {
std::cout << ">> myMosq - connected with server" << std::endl;
} else {
std::cout << ">> myMosq - Impossible to connect with server(" << rc << ")" << std::endl;
}
}
void myMosq::on_publish(int mid)
{
std::cout << ">> myMosq - Message (" << mid << ") succeed to be published " << std::endl;
}
本文链接地址:https://const.net.cn/163.html