centos MQTT安装和php使用mosquitto的实例
php安装mqtt 扩展
yum install -y php-devel
yum install -y mosquitto-devel
/usr/local/php/bin/pecl install Mosquitto-alpha
安装过程提示有3个函数被禁用
popen readlink putenv
可以开启后安装后再禁用也可以手动安装
有可能安装不成功也可以手动安装
cd /tmp/pear/download 进入下载的目录
tar zxvf Mosquitto-0.4.0.tgz 解压
cd Mosquitto-0.4.0 继续进入
phpize ./configure && make && make install
php.ini 添加 extension=mosquitto.so
重启php
mqtt.php
<?php $client = new Mosquitto\Client(); $client->setCredentials('root','12345'); $client->connect("127.0.0.1", 1884, 5); for($i = 0;$i<=100;$i++) { $client->loop(); $mid = $client->publish('ss', "Hello from PHP at " . date('Y-m-d H:i:s'), 1, 0); echo "Sent message ID: {$mid}\n"; $client->loop(); sleep(2); }
sub.php
<?php $c = new Mosquitto\Client; $c->setCredentials('root','12345'); $c->connect('127.0.0.1',1884,50); $c->subscribe('ss', 1); $c->onMessage(function($m) { var_dump($m); }); $c->loopForever();