安装mqtt
https://blog.csdn.net/qq_29933439/article/details/91307940
一. 为什么选择在ubuntu下安装服务器的原因
因为考虑后使用wireshark抓取MQTT数据包来进行对MQTT协议分析, mqtt客户端使用的是eclipse.paho.ui.app(安装在windows下,后续将介绍如何安装),如果将mqtt服务器安装在windows下,那么wireshark无法捕获localhost数据包(可能有其他办法搞定,总之没必要麻烦,而且将服务器安装在ubuntu一方面也可以模拟实际mqtt服务器在遥远的主机上的现实情况, 何乐而不为呢)。
二. ubuntu安装MQTT服务器
这里选择的是mosquitto
1.引入mosquitto仓库并更新
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
2. 更新依赖
sudo apt-get update (注意这里我使用root模式,避免后续权限麻烦)
3. 安装mosquitto
sudo apt-get install mosquitto
4. 查看mosquitto服务是否开启
sudo service mosquitto status
如果active显示running,至此说明mqtt服务器已成功开启 , 可以使用以下命令
开启/停止 mosquitto服务:
sudo service mosquitto start
sudo service mosquitto stop
*特别说明: 实验中的ubuntu(16.04)系统是安装VM虚拟机中,这里网络设置是选择桥接模式(后续wireshark抓包亲测可用,如读者使用NAT模式,如后续wireshark无法抓取包,可考虑该设置导致)
mosquitto简单的MQTT订阅发布:
订阅
//可能会提示安装 mosquitto_sub 根据提示安装就行
mosquitto_sub -h 192.168.1.175 -p 1883 -t mtopic
发布
//可能会提示安装 mosquitto_pub 根据提示安装就行
mosquitto_pub -h 192.168.1.175 -p 1883 -t mtopic -m “hello world111111”
mqtt安装完成后出现了问题,问题是使用发布
mosquitto_pub -h 127.0.0.1 -p 1883 -t mtopic -m “hello world111111”
mosquitto_sub -h 127.0.0.1 -p 1883 -t mtopic
这样是好使的,或者使用阿里云的外网ip是好使的,但是使用内网的192.168.1.175就不好使
(因为这样安装的是2.0以上版本的,2.0以下版本是好使的. 2.0.0大版本更新后如果不加载配件文件则使用回环接口(仅可用于本地Socket通信)。)
具体排查和解决方法如下:
因为mqtt默认端口是1883 , 查询1883端口使用情况发现, 监听的是localhost,说明只有localhost好使。
lsof -i | grep 1883
之后登陆mqtt也发现问题, 发现里面写了
Starting in local only mode. Connections will only be possible from clients running on this machine.
Create a configuration file which defines a listener to allow remote access.
发现只能本地连接, 之后百度查询解决方法, 发现了解决问题的方法
https://www.jianshu.com/p/943c422b72d4
三、解决方法
先修改软件安装目录中的配置文件mosquitto.conf然后加载配置文件来启动服务器。
配置端口号,编辑/etc/mosquitto/mosquitto.conf,搜索listener去掉行首的#并加上端口号,示例端口为1883
listener 1883
启用匿名访问,若不允许匿名访问则只有添加客户端鉴权信息才能接入。为简化测试我们启用匿名访问:将mosquitto.conf里的allow_anonymous选项改为true并保存
allow_anonymous true
加载配置文件启动服务器测试,执行命令mosquitto.exe -c mosquitto.conf -v,此时LOG上已经没了Starting in local only mode且非本地客户端可以正常接入了
按照百度的方法之后发现还是不好使,之后发现需要把监听的地址改成0.0.0.0 之后好使了, 所以需要匿名还需要监听是0.0.0.0
具体配置如下
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
#新增
allow_anonymous true
#新增
bind_address 0.0.0.0
include_dir /etc/mosquitto/conf.d
之后就好使了
订阅
mosquitto_sub -h 192.168.1.175 -p 1883 -t mtopic
发布
mosquitto_pub -h 192.168.1.175 -p 1883 -t mtopic -m “hello world111111”
安装simps
PHP >= 7.1
Swoole PHP 扩展 >= 4.4
PDO PHP 扩展 (如需要使用到 MySQL 客户端)
Redis PHP 扩展 (如需要使用到 Redis 客户端)
redis 客户端
这些都需要安装
使用的宝塔 还是比较快捷的
https://simps.io/#/zh-cn/install (根据文档安装就就行)
安装之后启动的时候发现错误 需要根据
https://simps.io/#/zh-cn/mqtt/client (客户端)
https://simps.io/#/zh-cn/mqtt/server (服务端)
php bin/simps.php mqtt:start
之后就能开启了,因为就使用客户端所以别的没用, 代码的话放到附件中
新建 subscribe.php (附件中有)就好使了