qt,mqtt,通信

总体步骤:1 new client(客户端),成功后,2 subjection(订阅),3 读写等操作;

1 client代码:

m_client = new QMqttClient(); // 获取client

//设定client

m_client->setHostname(“127.0.0.1”);

m_client->setPort(1883);

m_client->setUsername(“admin”);

m_client->setPassword(“123456”);

m_client->connectToHost();

方案A:

connect(m_client,SIGNAL(stateChanged(ClientState)),this,SLOT(slot_client()));

再slot中处理subjection;

方案 B:

// 延时2秒等待链路连接关闭

QTime reachTime = QTime::currentTime().addSecs(2);

while (QTime::currentTime() < reachTime)

{

if(m_client->state() == QMqttClient::Connected)

{

break;

}

//100ms 检测一次

QCoreApplication::processEvents(QEventLoop::AllEvents,100);

}

再订阅;

注意事项:

a 由于链接需要时间,所以直接在下面订阅,会订阅不上;所以有以上两个方案,链接成功后,才能订阅;

b 第一个方案是范例代码的方案,好处是可以确定client状态改变的时候,会调用slot函数;第二个方案是事件函数,当成功链接后会跳出循环,执行下面的语句,如果遇到断网重连的情况很会导致下面的语句被反复运行。

2 subjection代码:

m_sub = m_client->subscribe(topic);

if (!m_sub) {

qDebug()<<“sub can’t connect”<

return;

}

connect(m_sub,SIGNAL(messageReceived(QMqttMessage)),this,SLOT(slot_deal_msg(QMqttMessage)));

注意事项:

a写专门处理message的函数,用了接受message,并写专门解读数据的函数,获取想要的数据;

3 读写的代码:

if (m_client->publish(topic,msg)==-1)

qDebug()<<“send failed”<

读写操作的要点:

a写专门处理协议的函数(即生成msg的函数,把要send的数据用这个函数处理成协议);

你可能感兴趣的:(通信)