安装扩展前需安装Mosquitto
这里有MQTT服务器搭建-mosquitto1.4.4安装指南 https://www.cnblogs.com/littleatp/p/4835879.html
安装基础软件
yum install gcc-c++
yum install cmake
yum install openssl-devel //mosquitto默认支持openssl
下载程序
官网下载
wget http://mosquitto.org/files/source/mosquitto-1.4.4.tar.gz
tar -xzvf mosquitto-1.4.4.tar.gz
cd mosquitto-1.4.4
编译选项
当前的程序目录可直接编译,在编译之前需根据需要做一定的配置,否则会出现 xxx.h找不到的情况。
vim config.mk
安装c-areas
wget http://c-ares.haxx.se/download/c-ares-1.10.0.tar.gz
tar xvf c-ares-1.10.0.tar.gz
cd c-ares-1.10.0
./configure
make
sudo make install
安装lib-uuid
yum install libuuid-devel
安装libwebsockets
wget https://github.com/warmcat/libwebsockets/archive/v1.3-chrome37-firefox30.tar.gz
tar zxvf v1.3-chrome37-firefox30.tar.gz
cd libwebsockets-1.3-chrome37-firefox30
mkdir build; cd build;
cmake .. -DLIB_SUFFIX=64
make install
开始安装mosquitto
make
make install
然后安装php扩展
中文文档地址:https://www.kancloud.cn/liao-song/mosquitto-php/500401
github 上面有实例大家可以看看
https://github.com/mgdm/Mosquitto-PHP.git
中文官方文档 https://www.kancloud.cn/liao-song/mosquitto-php/500403
phpize
./configure --with-mosquitto=/path/to/libmosquitto
make
make install
然后添加extension=mosquitto.so到你的PHP配置文件php.ini中。
–with-mosquitto
是可选参数,只有当安装程序找不到libmosquitto拓展包,才需要添加这个参数
加上ssl协议
首先需要去签一个可信任的证书。目前腾讯云和阿里云都提供了免费证书申请。mosquitto配置ssl需要用到3个文件。
root.crt (根证书)
server.crt (我们自己的公钥根据根证书签的证书)
server.key (密钥)
获得这3个文件后,我们就可以配置mosquitto的ssl了。以下贴出主要的配置
vim /etc/mosquitto/mosquitto.conf
port 1883
listener 8883
cafile /home/yangjb/apache/1_root_bundle.crt
certfile /home/yangjb/apache/2_www.qilv.group.crt
keyfile /home/yangjb/apache/3_www.qilv.group.key
listener 8080
protocol websockets
listener 8081
protocol websockets
cafile /home/yangjb/apache/1_root_bundle.crt
certfile /home/yangjb/apache/2_www.qilv.group.crt
keyfile /home/yangjb/apache/3_www.qilv.group.key
配完重启mosquitto服务器就生效了
mqtt 协议走 1883端口
mqtt+ssl 走8883端口
websocket 协议走 8080端口
websocket+ssl 走8081端口
通过 nginx转发websockt
我这边测试都通过了,但是朋友的小程序一直连不上websocket。(ws+wss都连不上)
用微信自带的websocket库连接是可以的。但是他用的是Patho.Client库连接,就是死活连不上。
后来网上找了半天,发现一篇文章。说禁用Sec-WebSocket-Protocol头就可以了。然后我配了下nginx,转发请求的时候去掉Sec-WebSocket-Protocol头,竟然真的可以了。也不知道什么原理- -。下面附上部分主要的配置
location /mqtt {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Sec-WebSocket-Protocol mqtt;
# 这行就是去除 Sec-WebSocket-Protocol
more_clear_headers Sec-WebSocket-Protocol;
proxy_http_version 1.1;
proxy_set_header Upgrade websocket;
proxy_set_header Connection "upgrade";
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
}
启动mosquitto
cd /etc/mosquitto
cp mosquitto.conf.example mosquitto.conf
useradd mosquitto
mosquitto -c mosquitto.conf -d
作者:weylau
链接:https://www.jianshu.com/p/d90fa3b6a12c
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。