MQTT is a lightweight protocol to communicate with IoT devices connected to a network. Mosquitto is a popular MQTT server that can be used to publish and subscribe to MQTT topics. Here some startup and useful command are provided with example to help you get started with Mosquitto broker application.
# How to start Mosquitto server
To start the mosquitto server we can use the following command in windows command line terminal.
net start mosquitto
Eg:C:\Windows\system32\ net stop mosquitto
# How to stop Mosquitto server
We can stop mosquitto MQTT server using the command line terminal in windows and typing the following command.
net stop mosquitto
Eg: C:\Windows\system32\ net stop mosquitto
# Change MQTT broker port
To change the port number(default is 1883) we can use the following command in windows command terminal.
mosquitto -p 1884
Eg:
Publish and Subscribe Mosquitto Server
We can test the mosquitto server by publishing a topic message and subscribing to the topic using the mosquitto_pub and mosquitto_sub utilities.
First we publish a MQTT message using the following command on one terminal.
C:\Windows\system32> mosquitto_pub -h 192.168.1.5 -m "Hello Message" -t server/msg
where m option is for string message and the t option is for topic
We can then subscribe to the server topic published above with the command as follows.
C:\Windows\system32> mosquitto_sub -h 192.168.1.5 -t server/#
and we will receive the message Hello Message as shown below,
The subscribe command will continue to look for message until CRTL+C is pressed.
There are several option when we publish message as listed below.
-r Sets retain flag
-n Sends Null message useful for clearing retain message.
-p – Set Port number Default is 1883-d - debug option
-u – Provide a username
-P – Provide a password
-i – Provide client name
-I – Provide a client id prefix- Used when testing client restrictions using prefix security.
The following shows message published when debug option which shows the entire situation of the published message.
Publish with username and password example is provided below:
C:\Windows\system32> mosquitto_pub -h 192.168.1.5 -m "Hello Message" -t server/msg -d -u ee -P diary