How to send and receive messages with mosquitto_sub and mosquitto_pub to


1. Connecting with Mosquitto without using TLS

Follow next indications to connect with mosquitto_sub y mosquitto_pub to

  1. Create a couple of credentials if you do not have them (look at the following link: How to create and manage your MQTT devices with )

  2. You must create two credentials: one for sending and another to receive messages. If you want to reuse same credentials look at: How to skip MQTT connection replace, reusing same credentials

  3. Now, to connect (without using TLS), run the following command (replacing , y with your credentials):

    >> mosquitto_sub -h -i <client-id> -u <username-> -P '<password>' -t message/topic/to/subscribe -q 2

  4. Previous command will subscribe and print all messages received on that topic. Now, in another terminal and without stopping previous command, send messages with the following:

    >> mosquitto_pub -h -i <client2-id> -u <username2> -P '<password2>' -t message/topic/to/subscribe -m "hello world"

If everything went ok, you will see messages sent printed at the terminal running mosquitto_sub.

2. Connecting with Mosquitto using TLS

Now, to connect to using TLS and mosquitto_sub and mosquitto_pub you will have to add “-p 8883 --capath /etc/ssl/certs” like this:

`>> mosquitto_sub -h -p 8883 --capath /etc/ssl/certs -i <client-id> -u <username-> -P '<password>' -t message/topic/to/subscribe -q 2`

These options are:

  1. -p 8883 instruct mosquitto to connect to 8883 TLS port
  2. --capath instruct mosquitto where to find public root certificates to complete client certificate trust chain.
  3. These options (-p and --capath) must be configured on both commands (mosquitto_sub and mosquitto_pub).

Connecting to using mosquitto_sub/_pub and TLS from a MacOS/X

I tried #3 to connect and run with the following code in terminal command:
“mosquitto_sub -h -i client1 -u shahrasel -P ‘my_pass’ -t message/topic/to/subscribe -q 2”
it’s showing me “Connection error: Connection Refused: broker unavailable.”
Could you kindly tell me what mistake did I make?



See the following link for common errors with mosquitto_sub:

It seems you are using wrong clientId, userName or passwords.

Best Regards,