CloudAMQP with MQTT from the command line
The Mosquitto clients, mosquitto_pub and
mosquitto_sub, publish and subscribe from a terminal: a quick way to try
MQTT, check your connection details or watch a topic.
sudo apt-get install mosquitto-clients # Debian and Ubuntu
brew install mosquitto # macOS
Publish and subscribe
Set MQTT_HOST, MQTT_PORT, MQTT_USERNAME and MQTT_PASSWORD to the MQTT
details on your instance’s details page in the CloudAMQP console. Port 8883
uses TLS. Without them, the scripts connect to a local broker.
Save the publisher as publisher.sh:
#!/bin/sh
set -eu
port=${MQTT_PORT:-1883}
# Port 8883 uses TLS, verified against the system's certificates
[ "$port" = 8883 ] && set -- --tls-use-os-certs
# QoS 1 waits for the broker's PUBACK
mosquitto_pub "$@" -h "${MQTT_HOST:-localhost}" -p "$port" \
-u "${MQTT_USERNAME:-guest}" -P "${MQTT_PASSWORD:-guest}" \
-q 1 -t hello -m "Hello world!"
echo " [x] Sent 'Hello world!'"
Save the subscriber as worker.sh:
#!/bin/sh
set -eu
port=${MQTT_PORT:-1883}
# Port 8883 uses TLS, verified against the system's certificates
[ "$port" = 8883 ] && set -- --tls-use-os-certs
# Subscribes with QoS 1, and prints each message until you press CTRL+C
exec mosquitto_sub "$@" -h "${MQTT_HOST:-localhost}" -p "$port" \
-u "${MQTT_USERNAME:-guest}" -P "${MQTT_PASSWORD:-guest}" \
-q 1 -t hello -F " [x] Received '%p'"
Make them executable with chmod +x publisher.sh worker.sh, then run
./worker.sh in one terminal and ./publisher.sh in another.
A runnable example is in shell/mosquitto in cloudamqp/examples.
Good to know
- Put the vhost in the username, as
vhost:user. MQTT has no vhost of its own, and the console shows the username that way. - Use
--tls-use-os-certsfor TLS on port 8883. It verifies the server certificate against the system’s certificates; don’t add--insecure. - Use QoS 1 with
-q 1, somosquitto_pubwaits for the broker’s PUBACK. - Add
-dto see each packet, which helps when a connection fails.