ubuntu mosquitto安装与配置
以Ubuntu为例
添加到存储库列表
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa

更新软件包
sudo apt-get update

安装:sudo apt-get install mosquitto

发现我原来已经有了,先移除吧,装个新的。
移除:sudo apt-get remove mosquitto

再次执行安装:sudo apt-get install mosquitto

查看状态
sudo service mosquitto status

运行
sudo service mosquitto start

停止
sudo service mosquitto stop

安装命令行客户端,我用python写,不打算用现成的,这里就不装了。
sudo apt-get install mosquitto-clients
----------------------------
2. 配置用户名和密码,不允许匿名登陆:
官网说明:
https://mosquitto.org/documentation/authentication-methods/
https://mosquitto.org/man/mosquitto_passwd-1.html


现在打开终端,来到如下地址:

输入创建命令:sudo mosquitto_passwd -c ./passwd coolcall

用mqtt.fx测试连接:

开始修改
etc/mosquitto/mosquitto.conf配置文件

要修改的文件里添加(三行分别是:1、监听的端口;2、不允许匿名登陆;3、登陆账号信息的文件):
listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwd

点击保存后,打开ubuntu系统,启动mosquito:
sudo service mosquitto start #启动
sudo service mosquitto status #查看状态
sudo service mosquitto stop #关闭

启动后,mqtt.Fx连接:

到此为止,mosquito的用户配置就完成了,也可以直接用python代码进行连接。
import paho.mqtt.client as mqtt
import time
#HOST = "test.mosquitto.org"
HOST = "127.0.0.1"
PORT = 1883
def on_message_callback(client, userdata, message):
print(message.topic+" " + ":" + str(message.payload))
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# client.subscribe("coolcall")
client.subscribe("#")#订阅所有主题
def main():
client = mqtt.Client('test')
client.connect(HOST, PORT, 60)
client.username_pw_set('coolcall', '123123')
client.on_connect = on_connect
client.on_message = on_message_callback
client.loop_start()#起了一个新的线程用于 message 的接收,当内部的线程接收到 message 后再调用回调函数。
while (1):
time.sleep(2)
client.publish("coolcall", "666666666", 1)
# client.loop_forever()
if __name__ == '__main__':
main()
相关推荐
-
PHP8种变量类型的详细讲解2025-02-22 00:32:24
-
php+apache 和 php+nginx的区别2025-02-22 00:21:27
-
PHP:与workerman结合实现定时任务2025-02-22 00:15:57
-
Nginx的Rewrite规则与实例2025-02-22 00:15:39
-
MySql中身份证字段的简单脱敏介绍2025-02-22 00:15:36