ubuntu搭建mqtt服务器及验证

本文介绍了如何在Ubuntu系统中安装并启动mosquitto MQTT服务器,包括查看启动命令、在特定端口运行服务。同时,详细说明了使用mosquitto_sub进行订阅以及mosquitto_pub发布消息的过程,强调了主题在MQTT中的重要性,并提供了相关命令的实际操作示例。
  1. 安装mosquitto

    sudo apt install mosquitto
    sudo apt install libmosquitto-dev
    sudo apt install mosquitto-clients
    
  2. 启动mosquitto
    默认安装mosquitto后就会自动启动mosquitto进程,其配置文件在/etc/mosquitto下,默认监听端口为1883
    /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf
    查看mosquitto的启动命令

    # mosquitto -h
    mosquitto version 1.4.15 (build date Tue, 18 Jun 2019 11:42:22 -0300)
    
    mosquitto is an MQTT v3.1.1/v3.1 broker.
    
    Usage: mosquitto [-c config_file] [-d] [-h] [-p port]
    
     -c : specify the broker config file.   (配置文件路径)
     -d : put the broker into the background after starting. (后台运行)
     -h : display this help. (显示帮助)
     -p : start the broker listening on the specified port.
          Not recommended in conjunction with the -c option. (指定端口)
     -v : verbose mode - enable all logging types. This overrides
          any logging options given in the config file. (打印日志)
    
    See http://mosquitto.org/ for more information.
    

    执行:mosquitto -p 5678 -v,在本地端口5678上启动mosquitto服务,并在前台运行打印日志

  3. 订阅
    使用mosquitto_sub命令启动订阅,查看mosquitto_sub的启动命令

    # mosquitto_sub --help
    mosquitto_sub is a simple mqtt client that will subscribe to a single topic and pr
### 安装 Mosquitto MQTT 服务器Ubuntu 系统上,可以使用 Mosquitto 这个开源的 MQTT 消息代理来搭建 MQTT 服务器。首先,更新系统软件包列表并安装 Mosquitto: ```bash sudo apt update sudo apt install mosquitto ``` 安装完成后,Mosquitto 服务会自动启动。可以通过以下命令检查服务状态: ```bash systemctl status mosquitto ``` 如果服务未启动,可以使用以下命令手动启动: ```bash sudo systemctl start mosquitto ``` 为了确保 Mosquitto 在系统重启后自动运行,可以启用服务: ```bash sudo systemctl enable mosquitto ``` ### 配置 Mosquitto Mosquitto 的配置文件通常位于 `/etc/mosquitto/mosquitto.conf`。可以根据需要编辑此文件以更改默认设置,例如监听端口、持久化设置等。默认情况下,Mosquitto 使用端口 `1883`。 如果需要配置网络桥接模式,确保 Ubuntu 服务器与主机处于同一网段,以便双方可以互相 `ping` 通。这一步对于确保主机能够访问 MQTT 服务器非常重要 [^3]。 ### 测试 Mosquitto 服务器 安装并配置完成后,可以使用 Mosquitto 自带的客户端工具进行测试。在一个终端窗口中订阅一个主题: ```bash mosquitto_sub -h localhost -t "test/topic" ``` 在另一个终端窗口中发布一条消息到该主题: ```bash mosquitto_pub -h localhost -t "test/topic" -m "Hello, MQTT World!" ``` 如果一切正常,订阅者应该能够接收到发布的消息。 ### 安全性配置 对于生产环境,建议配置 SSL/TLS 加密和身份验证等安全措施。这可以通过修改 Mosquitto 的配置文件来实现,包括设置监听端口为 `8883`(用于 TLS 加密连接)以及配置用户名和密码认证 [^1]。 ### 使用 Python 客户端连接 如果希望使用 Python 编写客户端程序来连接 MQTT 服务器,可以使用 `paho-mqtt` 库。首先安装库: ```bash pip install paho-mqtt ``` 然后编写 Python 代码来连接服务器、订阅主题和发布消息 [^2]。 ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

togolife

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值