cpp code for receiving message

This commit is contained in:
ishak jmilou.ishak
2024-10-16 16:27:36 +02:00
parent 55c24eabf7
commit 2aeb41af7c

View File

@@ -1,52 +1,39 @@
#include <iostream> #include <iostream>
#include <boost/asio.hpp> #include "mqtt/async_client.h"
#include <string>
using boost::asio::ip::tcp; const std::string SERVER_ADDRESS("tcp://localhost:1883");
const std::string CLIENT_ID("pi_client");
const std::string TOPIC("button/pressed");
class callback : public virtual mqtt::callback
{
public:
void message_arrived(mqtt::const_message_ptr msg) override {
std::cout << "Message arrived: " << msg->get_payload_str() << std::endl;
}
};
int main() { int main() {
mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);
callback cb;
client.set_callback(cb);
mqtt::connect_options connOpts;
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(true);
try { try {
// Create an io_context object client.connect(connOpts)->wait();
boost::asio::io_context io_context; client.subscribe(TOPIC, 1)->wait();
}
// Resolve the server address and port catch (const mqtt::exception& exc) {
tcp::resolver resolver(io_context); std::cerr << "Error: " << exc.what() << std::endl;
tcp::resolver::results_type endpoints = resolver.resolve("127.0.0.1", "4024"); return 1;
// Create and connect the socket
tcp::socket socket(io_context);
boost::asio::connect(socket, endpoints);
std::cout << "Connected to the server." << std::endl;
// Receive initial message from the server
boost::asio::streambuf buffer;
boost::asio::read_until(socket, buffer, "\n");
std::istream is(&buffer);
std::string initial_message;
std::getline(is, initial_message);
std::cout << "Initial message from server: " << initial_message << std::endl;
// Send and receive messages
while (true) {
// Send a message to the server
std::string message;
std::cout << "Enter message: ";
std::getline(std::cin, message);
message += "\n"; // Add newline to mark the end of the message
boost::asio::write(socket, boost::asio::buffer(message));
// Receive a response from the server
boost::asio::streambuf response_buffer;
boost::asio::read_until(socket, response_buffer, "\n");
std::istream response_stream(&response_buffer);
std::string reply;
std::getline(response_stream, reply);
std::cout << "Reply from server: " << reply << std::endl;
} }
} catch (std::exception& e) { // Houd de verbinding actief
std::cerr << "Exception: " << e.what() << std::endl; while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
} }
return 0; return 0;