ubuntu mqtt客户端
时间: 2023-09-05 20:13:58 浏览: 151
mqtt 客户端
3星 · 编辑精心推荐
在Ubuntu上,你可以使用 Eclipse Paho 这个 MQTT 客户端库来实现 MQTT 客户端。
以下是在 Ubuntu 上安装 Paho MQTT 客户端库的步骤:
1. 打开终端并更新本地软件包列表:
```
sudo apt-get update
```
2. 安装 Paho MQTT 客户端库:
```
sudo apt-get install libssl-dev libcrypto++-dev libssl-doc
sudo apt-get install libpaho-mqtt-dev
```
3. 编写一个 MQTT 客户端代码,例如:
```
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <csignal>
#include "mqtt/async_client.h"
const std::string SERVER_ADDRESS { "tcp://localhost:1883" };
const std::string CLIENT_ID { "async_subcribe_cpp" };
class callback : public virtual mqtt::callback
{
void connection_lost(const std::string& cause) override
{
std::cout << "\nConnection lost" << std::endl;
if (!cause.empty())
std::cout << "\tcause: " << cause << std::endl;
}
void delivery_complete(mqtt::delivery_token_ptr token) override {}
mqtt::subscription_promise* sub_promise_;
public:
callback(mqtt::subscription_promise* sub_promise)
: sub_promise_(sub_promise) {}
void connected(const std::string& cause) override
{
std::cout << "Connection success" << std::endl;
sub_promise_->set_value(0);
}
void message_arrived(mqtt::const_message_ptr msg) override
{
std::cout << "Message arrived" << std::endl;
std::cout << "\ttopic: '" << msg->get_topic() << "'" << std::endl;
std::cout << "\tpayload: '" << msg->to_string() << "'\n" << std::endl;
}
};
int main(int argc, char* argv[])
{
mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);
mqtt::connect_options connOpts;
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(true);
mqtt::subscription_promise sub_promise;
mqtt::subscription_options subOpts;
subOpts.set_no_local(true);
subOpts.set_qos(1);
callback cb(&sub_promise);
client.set_callback(cb);
try {
std::cout << "Connecting to the MQTT server..." << std::endl;
mqtt::token_ptr conntok = client.connect(connOpts);
conntok->wait();
std::cout << "Connected" << std::endl;
mqtt::token_ptr subtok = client.subscribe("test", subOpts);
subtok->wait();
std::cout << "Subscribed to topic 'test'" << std::endl;
sub_promise.get_future().wait();
while (true) {}
}
catch (const mqtt::exception& exc) {
std::cerr << "MQTT Exception: " << exc.what() << std::endl;
return 1;
}
return 0;
}
```
4. 编译并运行 MQTT 客户端代码:
```
g++ -o mqtt_client mqtt_client.cpp -lpaho-mqtt3a -lpaho-mqttpp3
./mqtt_client
```
以上代码实现了一个 MQTT 订阅者客户端,它将连接到本地主机上的 MQTT 代理,并订阅名为“test”的主题。当有新消息到达“test”主题时,客户端将输出消息的主题和有效负载。
阅读全文