运行mosquitto
mosquitto安装完之后,直接在命令行运行以下指令
sunrise@ubuntu:~$ mosquitto
1722580370: mosquitto version 2.0.18 starting
1722580370: Using default config.
1722580370: Starting in local only mode. Connections will only be possible from clients running on this machine.
1722580370: Create a configuration file which defines a listener to allow remote access.
1722580370: For more details see https://mosquitto.org/documentation/authentication-methods/
1722580370: Opening ipv4 listen socket on port 1883.
1722580370: Opening ipv6 listen socket on port 1883.
1722580370: mosquitto version 2.0.18 running
此时,mosquitto以本地模式启动,只接受本机的客户端连接,如果我们需要远程接入,则需要配置一下mosquitto
配置mosquitto
首先,找到配置文件所在的目录
cd /usr/local/etc/mosquitto/
查看此目录下的全部文件
sunrise@ubuntu:/usr/local/etc/mosquitto$ ls
aclfile.example mosquitto.conf pskfile.example pwfile.example
打开mosquitto.conf文件,修改以下配置项
sudo vim mosquitto.conf
将其中的配置选项allow_anonymous改为 false,禁止匿名登录
将密码配置选项配置为/usr/local/etc/mosquitto/pwfile
将监听端口改为1833
allow_anonymous false
password_file /usr/local/etc/mosquitto/pwfile
listener 1883
将pwfile.example拷贝一份命名为pwfile
sudo cp pwfile.example pwfile
创建用户名和密码,这里创建的用户名为sunrise,密码为123,在命令窗口入如下命令
mosquitto_passwd -c /usr/local/etc/mosquitto/pwfile sunrise
执行以后会提示输入密码,重复2次输入之后,用户名密码配置完成
之后需要重新启动mosquitto服务
mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf
测试mosquitto
新起一个终端用于接收mqtt消息
mosquitto_sub -t test -u sunrise -P 123
我们可以在笔记本安装MQTTX用于测试mqtt连接,修改软件配置如下,根据实际情况填入服务器相关信息:
配置完成后点击Connect按钮,不出意外的话我们就可以连接上配置好的mqtt服务了。
修改topic为test后点击发送即可在终端收到发布的消息了。
sunrise@ubuntu:~$ mosquitto_sub -t test -u sunrise -P 123
{
"msg": "hello"
}