mqttpp_chat.cpp 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. // mqttpp_chat.cpp
  2. //
  3. // This is a Paho MQTT C++ client, sample application.
  4. //
  5. // The "chat" application is practically the "Hello World" application for
  6. // messaging systems. This allows a user to type in message to send to a
  7. // "group" while seeing all the messages that the other members of the group
  8. // send.
  9. //
  10. // This application is an MQTT publisher/subscriber using the C++
  11. // asynchronous client interface, employing callbacks to receive messages
  12. // and status updates.
  13. //
  14. // The sample demonstrates:
  15. // - Connecting to an MQTT server/broker.
  16. // - Publishing messages.
  17. // - Subscribing to a topic
  18. // - Receiving messages (callbacks) through a lambda function
  19. //
  20. // USAGE:
  21. // mqttpp_chat <user> <group>
  22. /*******************************************************************************
  23. * Copyright (c) 2019 Frank Pagliughi <fpagliughi@mindspring.com>
  24. *
  25. * All rights reserved. This program and the accompanying materials
  26. * are made available under the terms of the Eclipse Public License v1.0
  27. * and Eclipse Distribution License v1.0 which accompany this distribution.
  28. *
  29. * The Eclipse Public License is available at
  30. * http://www.eclipse.org/legal/epl-v10.html
  31. * and the Eclipse Distribution License is available at
  32. * http://www.eclipse.org/org/documents/edl-v10.php.
  33. *
  34. * Contributors:
  35. * Frank Pagliughi - initial implementation and documentation
  36. *******************************************************************************/
  37. #include <iostream>
  38. #include <cstdlib>
  39. #include <string>
  40. #include <cstring>
  41. #include <cctype>
  42. #include <thread>
  43. #include <chrono>
  44. #include "mqtt/async_client.h"
  45. #include "mqtt/topic.h"
  46. /////////////////////////////////////////////////////////////////////////////
  47. int main(int argc, char* argv[])
  48. {
  49. // The broker/server address
  50. const std::string SERVER_ADDRESS("tcp://localhost:1883");
  51. // The QoS to use for publishing and subscribing
  52. const int QOS = 1;
  53. // Tell the broker we don't want our own messages sent back to us.
  54. const bool NO_LOCAL = true;
  55. if (argc != 3) {
  56. std::cout << "USAGE: mqttpp_chat <user> <group>" << std::endl;
  57. return 1;
  58. }
  59. std::string chatUser { argv[1] },
  60. chatGroup { argv[2] },
  61. chatTopic { "chat/"+chatGroup };
  62. // LWT message is broadcast to other users if out connection is lost
  63. auto lwt = mqtt::make_message(chatTopic, "<<<"+chatUser+" was disconnected>>>", QOS, false);
  64. // Set up the connect options
  65. mqtt::connect_options connOpts;
  66. connOpts.set_keep_alive_interval(20);
  67. connOpts.set_mqtt_version(MQTTVERSION_5);
  68. connOpts.set_clean_start(true);
  69. connOpts.set_will_message(lwt);
  70. mqtt::async_client cli(SERVER_ADDRESS, "");
  71. // Set a callback for connection lost.
  72. // This just exits the app.
  73. cli.set_connection_lost_handler([](const std::string&) {
  74. std::cout << "*** Connection Lost ***" << std::endl;
  75. exit(2);
  76. });
  77. // Set the callback for incoming messages
  78. cli.set_message_callback([](mqtt::const_message_ptr msg) {
  79. std::cout << msg->get_payload_str() << std::endl;
  80. });
  81. // We publish and subscribe to one topic,
  82. // so a 'topic' object is helpful.
  83. mqtt::topic topic { cli, "chat/"+chatGroup, QOS };
  84. // Start the connection.
  85. try {
  86. std::cout << "Connecting to the chat server at '" << SERVER_ADDRESS
  87. << "'..." << std::flush;
  88. auto tok = cli.connect(connOpts);
  89. tok->wait();
  90. // Subscribe to the topic using "no local" so that
  91. // we don't get own messages sent back to us
  92. std::cout << "Ok\nJoining the group..." << std::flush;
  93. auto subOpts = mqtt::subscribe_options(NO_LOCAL);
  94. topic.subscribe(subOpts)->wait();
  95. std::cout << "Ok" << std::endl;
  96. }
  97. catch (const mqtt::exception& exc) {
  98. std::cerr << "\nERROR: Unable to connect. "
  99. << exc.what() << std::endl;
  100. return 1;
  101. }
  102. // Let eveyone know that a new user joined the conversation.
  103. topic.publish("<<" + chatUser + " joined the group>>");
  104. // Read messages from the console and publish them.
  105. // Quit when the use enters an empty line.
  106. std::string usrMsg;
  107. while (std::getline(std::cin, usrMsg) && !usrMsg.empty()) {
  108. usrMsg = chatUser + ": " + usrMsg;
  109. topic.publish(usrMsg);
  110. }
  111. // Let eveyone know that the user left the conversation.
  112. topic.publish("<<" + chatUser + " left the group>>")->wait();
  113. // Disconnect
  114. try {
  115. std::cout << "Disconnecting from the chat server..." << std::flush;
  116. cli.disconnect()->wait();
  117. std::cout << "OK" << std::endl;
  118. }
  119. catch (const mqtt::exception& exc) {
  120. std::cerr << exc.what() << std::endl;
  121. return 1;
  122. }
  123. return 0;
  124. }