[MQTT]部署mosquitto服务

一,部署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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值