1.安装相关依赖
yum install gcc gcc-c++ openssl-devel c-ares-devel libuuid-devel wget cmake build-essential python quilt devscripts python-setuptools python3 libssl-dev libc-ares-dev uuid-dev daemon openssl-devel
2.下载源码
wget http://mosquitto.org/files/source/mosquitto-1.4.9.tar.gz
3.解压
tar zxfv mosquitto-1.4.9.tar.gz
4.进入文件
5.编译
make
6.安装
make install
7.在php.ini中加入
extension=mosquitto.so
8.重启php 服务器 查看phpinfo
注意点:
1.找不到libmosquitto.so.1
使用中可能会出现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
测试:
1.启动代理服务
mosquitto -v -v打印更多的调试信息
2.订阅一个主题
mosquitto_sub -v -t cs -t指定主题,订阅了主题为cs -v打印更多的调试信息
3.发布内容
mosquitto_pub -t cs -m hello,world -t指定主题为cs -m指定消息内容
当发布完成后在切换到订阅窗口查看
切换到调试窗口
Demo测试
pub.php
<?php
$client = new Mosquitto\Client();
$client->setCredentials('root','root');//服务器的账号密码
$client->connect("192.168.52.133", 1883, 5);//修改成自己的服务器地址
for($i = 0;$i<=10;$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','root');
$c->connect('192.168.52.133', 1883, 50);
$c->subscribe('ss', 1);
$c->onMessage(function($m) {
var_dump($m);
});
$c->loopForever();
demo 测试步骤
1.在窗口执行 mosquitto -v
2.另起窗口执行pub.php文件
3.另起窗口hi执行sub.php文件