2 years ago
#74452

user17477528
MQTT Mosquitto C++ not publishing data (disconnecting before)
I am trying to publish a message both using commands and coding it. With the commands it works fine, I have a Broker running and a Publisher:
mosquitto -v
mosquitto_pub -d -t testTopic -m "Hello"
Then, on the Broker I get a nice response and can read the data in a subscriber correctly:
1642677548: New connection from ::1:60619 on port 1883.
1642677548: New client connected from ::1:60619 as auto-49A467C1-9AB0-9F4D-FEBD-6C99AB992163 (p2, c1, k60).
1642677548: No will message specified.
1642677548: Sending CONNACK to auto-49A467C1-9AB0-9F4D-FEBD-6C99AB992163 (0, 0)
1642677548: Received PUBLISH from auto-49A467C1-9AB0-9F4D-FEBD-6C99AB992163 (d0, q0, r0, m0, 'testTopic', ... (5 bytes))
1642677548: Received DISCONNECT from auto-49A467C1-9AB0-9F4D-FEBD-6C99AB992163
1642677548: Client auto-49A467C1-9AB0-9F4D-FEBD-6C99AB992163 disconnected.
But having it in code as:
int main() {
int rc;
struct mosquitto* mosq;
mosquitto_lib_init();
mosq = mosquitto_new(NULL, true, NULL);
rc = mosquitto_connect(mosq, "localhost", 1883, 60);
if (rc != 0) {
std::cout << "Client could not connect to broker!";
mosquitto_destroy(mosq);
return -1;
}
mosquitto_loop_start(mosq);
mosquitto_publish(mosq, NULL, "testTopic", 6, "Hello", 0, false);
mosquitto_disconnect(mosq);
mosquitto_loop_stop(mosq, false);
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 0;
}
Doesn't work, it outputs in the Broker:
1642677347: New connection from ::1:60611 on port 1883.
1642677347: New client connected from ::1:60611 as auto-92BFFD6D-3C20-0BB1-C33D-4B251C137D04 (p2, c1, k60).
1642677347: No will message specified.
1642677347: Sending CONNACK to auto-92BFFD6D-3C20-0BB1-C33D-4B251C137D04 (0, 0)
1642677347: Client auto-92BFFD6D-3C20-0BB1-C33D-4B251C137D04 closed its connection.
Is there something wrong in the code or am I missing something here? (P.s. using Windows.)
c++
mqtt
mosquitto
0 Answers
Your Answer