centos7安装mosquitto及测试代码

Home / Article MrLee 2021-12-8 2385

使用的是云服务器是centos7,所以直接使用命令行安装。省去下载代码再编译的过程。

yum install mosquitto

安装完成之后会默认添加mosquitto用户,这步可以省略。默认配置在/etc/mosquitto/mosquitto.conf,默认只支持tcp协议,websocket是不支持的,需要修改这个配置文件。这里给个参考,在Default listener下面添加:

# =================================================================
# Default listener
# =================================================================
# IP address/hostname to bind the default listener to. If not
# given, the default listener will not be bound to a specific
# address and so will be accessible to all network interfaces.
# bind_address ip-address/host name
#bind_address
# Port to use for the default listener.
port 1883
listener 9001
protocol websockets

然后使用这个配置启动即可。

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

参数-d表示后台运行。

附件有js版测试端,也可以使用paho-eclipse的tcp端测试

百度云网盘地址:https://pan.baidu.com/s/1i6MrK_J8Kn6TvEKRyGU-nw
提取码:tzv7

测试地址:

tcp地址:tcp://mqtt.it72.com:1883

websocket:ws://mqtt.it72.com:9001

yum install mosquitto安装后,就自带了mqtt客户端和服务端

mosquitto_sub -h sys.aiotos.net -t "iotostest" -v -u admin -P public
mosquitto_pub -h sys.aiotos.net -t "iotostest" -m "hello iotos" -u admin -P publi

以上测试订阅和发布消息命令

其中,指令使用分别解释如下:

1)订阅主题

mosquitto_sub  -h localhost -t "iotos_test" -v -u admin -P public

//mosquitto_sub : 订阅主题命令

//-h : 指定连接的MQTT服务器 ,此处使用本地主机localhost

//-t : 指定订阅的主题,此处为mqtt

//-v : 打印更多的调试信息

// -u  指定broker访问用户

// -P  指定broker访问密码

2)发布主题

mosquitto_pub  -h localhost -t "iotos_test" -m "hello iotos" -u admin -P public

//mosquitto_pub : 发布消息的命令

//-h : 指定连接的MQTT服务器,此时使用本地主机

//-t : 指定订阅的主题,从处为mqtt

//-m : 指定发布的消息,此处为"hello mqtt

// -u  指定broker访问用户

// -P  指定broker访问密码

MQTT-Client-Examples-master.zip超多版本的例子



配置用户名密码验证

mosquitto

配置用户名密码验证

mosquitto配置文件中指定密码文件,此处使用最简单的账号密码登录,不涉及TLS等加密选项。

修改配置文件

修改mosquitto.conf

# vi /etc/mosquitto/mosquitto.conf
# 关闭匿名模式
allow_anonymous false
# 指定密码文件
password_file /etc/mosquitto/pwfile.conf

修改用户名密码文件

# touch /etc/mosquitto/pwfile.conf
// 使用mosquitto_passwd命令创建用户,第一个lxy是用户名,第二个lxy是密码
# mosquitto_passwd -b /etc/mosquitto/pwfile.conf lxy lxy
// 重启mosquitto
# service mosquitto restart

订阅测试

此时订阅主题需要用密码,不用密码的话会提示not authorised。

root@ubuntu:~# mosquitto_sub -t "#" 
Connection Refused: not authorised.
root@ubuntu:~# mosquitto_sub -t "#" -u lxy -P lxy -v
notifications129 0
notifications130 1
notifications131 1

发布测试

发布消息也需要用密码

root@ubuntu:/etc/mosquitto# mosquitto_pub -t "topic/128" -m "i'm 128, msg to 128"
Connection Refused: not authorised.
Error: The connection was refused.
root@ubuntu:/etc/mosquitto# mosquitto_pub -t "topic/128" -m "i'm 128, msg to 128" -u lxy -P lxy


本文链接:https://www.it72.com/12706.htm

上传的附件:
推荐阅读
最新回复 (0)
返回