centos MQTT安装和php使用mosquitto的实例
MQTT 是物联网的消息传送协议标准。
在 CentOS 7上常用的开源 MQTT 消息服务器就是 Mosquitto
有人用 PECL 来安装 Mosquitto 的 PHP 实现,反正我没有成功
pecl install Mosquitto-alpha
也可以用yum安装
yum install -y epel-release yum search mosquitto yum install -y mosquitto mosquitto-devel yum install -y php-devel yum install -y mosquitto-devel
如果安装不成功就用编译安装
包下载地址:https://github.com/mgdm/Mosquitto-PHP
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',1883,50); $c->subscribe('ss', 1); $c->onMessage(function($m) { var_dump($m); }); $c->loopForever();