一,部署mosquitto服务
安装工具
sudo apt-get install libssl-dev libc-ares-dev uuid-dev
下载 Mosquitto
wget http://mosquitto.org/files/source/mosquitto-1.4.13.tar.gz
解压
tar xzvf mosquitto-1.4.13.tar.gz
安装
cd mosquitto-1.4.13/
make -ju
sudo make install
使用过程中找不到libmosquitto.so.1
error while loading shared libraries: libmosquitto.so.1: cannot open shared object file: No such file or directory
【解决方法】——修改libmosquitto.so位置
创建链接并更新动态链接库
sudo ln -s /usr/local/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1
sudo ldconfig
启动服务
mosquitto -c /etc/mosquitto/mosquitto.conf.example
调试命令示例
订阅
mosquitto_sub -h localhost -t TAG
发布
mosquitto_pub -h localhost -t TAG -m test
二,安装php的mqtt扩展
安装php工具
sudo apt install php-pear php7.0-dev
安装扩展
sudo pecl install Mosquitto-alpha
配置扩展,打开下面两个文件
sudo vim /etc/php/7.0/apache2/php.ini
sudo vim /etc/php/7.0/cli/php.ini
文件末尾添加
extension=mosquitto.so
重启服务
sudo service apache2 restart
发布消息示例代码
<?php
$client = new Mosquitto\Client();
$client->connect("localhost", 1883, 5);
$client->loop();
$mid = $client->publish('/hello', "Hello from PHP at " . date('Y-m-d H:i:s'), 1, 0);
$client->loop();
$client->disconnect();
接收消息示例代码
<?php
$client = new Mosquitto\Client();
$client->onMessage('message');
$client->connect("localhost", 1883, 5);
$client->subscribe('#', 1);
$client->loopForever();
function message($message) {
printf("Got a message on topic %s with payload:\n%s\n", $message->topic, $message->payload);
}
SSL配置如下(/etc/mosquitto/):
#cafile /etc/ssl/key/server_chain.crt
capath /etc/ssl/key/
# Path to the PEM encoded server certificate.
certfile /etc/ssl/key/server.crt
# Path to the PEM encoded keyfile.
keyfile /etc/ssl/key/server.key
可以用wget https://github.com/owntracks/tools/raw/master/TLS/generate-CA.sh 生成server和client端的key。
示例代码及相关文档:
https://github.com/mgdm/Mosquitto-PHP
http://mosquitto-php.readthedocs.io/en/latest/
https://github.com/mqtt/mqtt.github.io/wiki/libraries
http://blog.csdn.net/peakguy/article/details/71634842