最新动态 > 详情

php mosquitto(mqtt)完整简洁版

发布时间:2019-10-15 09:54:00

相关简介可以查看原来文章http://forpastime.com/news/18.html,相对写得复杂

一、安装和使用 MQTT
1 安装
我安装的为mosquitto-1.6.7

cd /usr/local/
# 下载源代码包
wget http://mosquitto.org/files/source/mosquitto-1.6.7.tar.gz
# 解压
tar zxfv mosquitto-1.6.7.tar.gz
mv mosquitto-1.6.7 mosquitto
# 进入目录
cd mosquitto

# 编译
make
# 安装
sudo make install
可以看到最后几行,说明在/etc/下创建了配置文件和密码文件,后面可以使用,也可以就使用mosquitto/当前目录下的配置
install -m 644 mosquitto.conf "/etc/mosquitto/mosquitto.conf.example"
install -m 644 aclfile.example "/etc/mosquitto/aclfile.example"
install -m 644 pwfile.example "/etc/mosquitto/pwfile.example"
install -m 644 pskfile.example "/etc/mosquitto/pskfile.example"

如果选择用当前目录下的配置:
复制一份新的密码文件
cp pwfile.example pwfile
修改配置文件
vi mosquitto.conf
#必须使用密码  搜索allow_anonymous  去掉前面#号
allow_anonymous false
#密码文件 搜索 password_file
password_file /usr/local/mosquitto/pwfile
权限
#user mosquitto
user root
端口
# Port to use for the default listener.
port 1884

:wq

生成密码
cd src
./mosquitto_passwd -c /usr/local/mosquitto/pwfile user_name
连续输入两次没密码
可以发现之前pwfile里面有了内容

启动并后台运行mosquitto
./mosquitto -d -c ../mosquitto.conf

查看是否开启
ps -aux | grep mosquitto

whereis mosquitto_sub

cd /usr/local/bin
./mosquitto_sub -h 127.0.0.1 -u user_name-P passwd-p 1184 -v -t uid_login

订阅如果遇到报错
./mosquitto_sub: error while loading shared libraries: libmosquitto.so.1: cannot open shared object file: No such file or directory
解决办法 
 sudo ln -s /usr/local/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1
更新动态链接库

sudo ldconfig
重新开个窗口
./mosquitto_pub -h 127.0.0.1 -u user_name-P passwd -p 1184 -t uid_login  -m 12

之前订阅的窗口收到信息说明成功

二、安装php mqtt扩展

pecl install Mosquitto-alpha
一般这只是下载了扩展包
cd /tmp/pecl/download
tar zxvf Mosquitto-0.4.0.tgz

cd Mosquitto-0.4.0

这里注意,如果是使用多php版本
php -v
看准使用的php版本,我这里用的是宝塔:

/www/server/php/72/bin/phpize
./configure --with-php-config=/www/server/php/72/bin/php-config
make
make install

php.ini 加入mosquitto.so

php -m看到有mosquitt则成功,

如果报错:
Module compiled with module API=20131226
PHP    compiled with module API=20170718

则是因为php多版本造成
cd /tmp/pecl/download

删掉整个文件重来
rm -rvf Mosquitto-0.4.0
再走第①步


vi mqtt.php
<?php
    $client = new Mosquitto\Client;
    $client->setCredentials('user_name','passwd');
    $client->connect(127.0.0.1, 1184, 5);//MQTT_IP是mqtt服务器ip  MQTT_PORT一般是1883
    $client->loop();
    $client->publish('uid_login', 'hhh', 1, 0);
    $client->disconnect();//断开链接
    unset($client);

php mqtt.php
查看刚刚订阅窗口
打印出 hhh
至此,php mqtt扩展也安装成功

上一篇: VM esxii配置centos虚拟机并配置lnmp环境

下一篇:centeos8 安装jdk1.8+tomcat9或者说是解决centos8安装tomcat后修改jre_home,tomcat安装后无法启动的问题