// async_consume.cpp // // This is a Paho MQTT C++ client, sample application. // // This application is an MQTT consumer/subscriber using the C++ // asynchronous client interface, employing the to receive messages // and status updates. // // The sample demonstrates: // - Connecting to an MQTT server/broker. // - Subscribing to a topic // - Receiving messages through the synchronous queuing API // /******************************************************************************* * Copyright (c) 2013-2017 Frank Pagliughi * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Frank Pagliughi - initial implementation and documentation *******************************************************************************/ #include #include #include #include #include #include #include #include "mqtt/async_client.h" using namespace std; const string SERVER_ADDRESS { "tcp://test.mosquitto.org:1883" }; const string CLIENT_ID { "async_consume" }; const string TOPIC { "baiyu" }; const int QOS = 1; ///////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { mqtt::connect_options connOpts; connOpts.set_keep_alive_interval(20); connOpts.set_clean_session(true); mqtt::async_client cli(SERVER_ADDRESS, CLIENT_ID); try { cout << "Connecting to the MQTT server..." << flush; cli.connect(connOpts)->wait(); cli.start_consuming(); cli.subscribe(TOPIC, QOS)->wait(); cout << "OK" << endl; // Consume messages while (true) { auto msg = cli.consume_message(); if (msg->to_string() == "quit") break; cout << msg->get_topic() << ": " << msg->to_string() << endl; } // Send messages // Disconnect cout << "\nShutting down and disconnecting from the MQTT server..." << flush; cli.unsubscribe(TOPIC)->wait(); cli.stop_consuming(); cli.disconnect()->wait(); cout << "OK" << endl; } catch (const mqtt::exception& exc) { cerr << exc.what() << endl; return 1; } return 0; }