Mosquitto 搭建及配置

Mosquitto 搭建及配置

 

Eclipse Mosquitto是一个开源消息代理,实现了MQTT协议版本3.1和3.1.1。Mosquitto轻量,适用于低功耗单板计算机到完整服务器的所有设备。Mosquitto项目还提供了用于实现MQTT客户端的C库以及非常受欢迎的mosquitto_pub和mosquitto_sub命令行MQTT客户端。

其他服务器代理实现:https://github.com/mqtt/mqtt.github.io/wiki/servers
各操作系统安装指引:https://mosquitto.org/download/

1. 下载安装

以Ubuntu16为例

  • 添加到存储库列表
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
  • 更新软件包
sudo apt-get update
  • 安装
sudo apt-get install mosquitto
  • 安装命令行客户端
sudo apt-get install mosquitto-clients

2. 配置

2.1 主配置文件mosquitto.conf

pid_file /var/run/mosquitto.pid

# 消息持久存储
persistence true
persistence_location /var/lib/mosquitto/

# 日志文件
log_dest file /var/log/mosquitto/mosquitto.log

# 其他配置
include_dir /etc/mosquitto/conf.d

# 禁止匿名访问
allow_anonymous false
# 认证配置
password_file /etc/mosquitto/pwfile
# 权限配置
acl_file /etc/mosquitto/aclfile

2.2 认证配置pwfile

  • 没有则创建文件
touch /etc/mosquitto/pwfile
  • 服务开启后,输入如下命令,根据提示输入两遍密码
mosquitto_passwd /etc/mosquitto/pwfile 用户名

2.3 权限配置aclfile

  • 打开文件
vim /etc/mosquitto/aclfile
  • 编辑内容
# 李雷只能发布以test为前缀的主题,订阅以$SYS开头的主题即系统主题
user lilei
topic write test/#
topic read $SYS/#

# 韩梅梅只能订阅以test为前缀的主题
user hanmeimei
topic read test/#

3. 启动

-c:指定特定配置文件启动
-d:后台运行

mosquitto -c /etc/mosquitto/mosquitto.conf -d

4. 测试

发布使用mosquitto_pub命令,订阅使用mosquitto_sub命令。常用参数介绍:

参数描述
-h服务器主机,默认localhost
-t指定主题
-u用户名
-P密码
-i客户端id,唯一
-m发布的消息内容

订阅

mosquitto_sub -h localhost -t "test/#" -u hanmeimei -P 123456 -i "client1"

订阅系统主题

# 订阅客户端存活连接数
mosquitto_sub -h localhost –t '$SYS/broker/clients/active' -u lilei -P 123456 -i "client2"

发布

mosquitto_pub -h localhost -t "test/abc" -u lilei -P 123456 -i "client3" -m "How are you?"

链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
搭建配置Mosquitto服务器,您可以按照以下步骤进行操作: 1. 安装Mosquitto服务器: - 在Linux上,可以使用包管理器进行安装。例如,在Ubuntu上,可以运行以下命令: ``` sudo apt-get update sudo apt-get install mosquitto ``` - 在Windows上,可以从Mosquitto官方网站下载二进制文件并进行安装。 2. 配置Mosquitto服务器: - 在Linux上,Mosquitto配置文件通常位于`/etc/mosquitto/mosquitto.conf`。您可以使用任何文本编辑器打开此文件进行编辑。 - 在Windows上,Mosquitto配置文件通常位于安装目录的`mosquitto.conf`文件中。 3. 配置Mosquitto服务器认证: - 在配置文件中,您可以设置用户名和密码进行认证。例如,在配置文件中添加以下内容以启用基本认证: ``` password_file /path/to/password_file ``` 将`/path/to/password_file`替换为存储用户名和密码的文件的路径。 - 接下来,在命令行中使用`mosquitto_passwd`命令创建一个密码文件,并设置用户名和密码。例如,运行以下命令: ``` mosquitto_passwd -c /path/to/password_file username ``` 将`/path/to/password_file`替换为密码文件的路径,`username`替换为您想要的用户名。然后会提示您输入密码。 4. 启动Mosquitto服务器: - 在Linux上,可以使用以下命令启动Mosquitto服务器: ``` sudo systemctl start mosquitto ``` - 在Windows上,可以通过运行Mosquitto安装目录中的`mosquitto.exe`可执行文件来启动服务器。 5. 连接和测试Mosquitto服务器: - 您可以使用任何MQTT客户端工具来连接和测试Mosquitto服务器,例如MQTT.fx或MQTT.js等。 - 请确保在连接时使用正确的主机名、端口号和凭据(如果已启用认证)。 这些步骤应该能帮助您搭建配置Mosquitto服务器。如果需要更详细的说明,请查阅Mosquitto官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值