MQTT代理服务器--mosquitto的搭建

Mosquitto是一个实现了MQTT3.1协议的代理服务器,由MQTT协议创始人之一的Andy Stanford-Clark开发,它为我们提供了非常棒的轻量级数据交换的解决方案。本文的主旨在于记录Mosquitto服务的安装和使用,以备日后查阅。

Linux下安装mosquitto(本文使用操作系统Ubuntu14.04)
下载地址(非最新版本):

wget http://mosquitto.org/files/source/mosquitto-1.4.9.tar.gz

解压:

tar zxfv mosquitto-1.4.9.tar.gz

编译

cd  mosquitto-1.4.9
make

在编译时可能出现错误./mosquitto_internal.h:40:20: fatal error: ares.h: No such file or directory
解决方法:打开mosquitto-1.4.9中的config.mk文件,将WITH_SRV:=yes中的yes改成no
安装

sudo make install

到此mosquitto代理就安装完成了!
接下来做一个测试:
一个完整的MQTT示例包括一个代理器,一个发布者和一个订阅者。测试分为以下几个步骤:
【1】启动服务mosquitto。
【2】订阅者通过mosquitto_sub订阅指定主题的消息。
【3】发布者通过mosquitto_pub发布指定主题的消息。
【4】代理服务器把该主题的消息推送到订阅者。

在这里插入图片描述
1.启动代理服务:mosquitto -v
同时可用选项-h获取帮助信息:

zhanghang@Ubuntu-14:~$ mosquitto -h
mosquitto version 1.4.9 (build date 2019-03-09 17:24:09+0800)

mosquitto is an MQTT v3.1 broker.

Usage: mosquitto [-c config_file] [-d] [-h] [-p port]

 -c : specify the broker config file.
 -d : put the broker into the background after starting.
 -h : display this help.
 -p : start the broker listening on the specified port.
      Not recommended in conjunction with the -c option.
 -v : verbose mode - enable all logging types. This overrides
      any logging options given in the config file.

2.订阅主题:testtopic
再打开一个终端:

mosquitto_sub  -h 127.0.0.1 -p 1883 -v -t testtopic

3.发布消息helloword到主题testtopic

mosquitto_pub  -h 127.0.0.1 -p 1883 -t testtopic -m helloworld     

此时在二号终端可收到testtopic主题的message

zhanghang@Ubuntu-14:~$  mosquitto_sub  -h 127.0.0.1 -p 1883 -v -t testtopic
testtopic helloworld

可能出现的问题:使用过程中找不到 libmosquitto.so.1error 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

再用软件mqtt.fx对其进行测试:
软件下载地址:http://mqttfx.jensd.de/index.php/download
下载一个自己喜欢的版本注意系统架构32bit或64bit;
运行程序:
在这里插入图片描述
点击齿轮状图标:选择local mosquitto,由于我实在是在windows上运行此程序,而ubuntu在虚拟机下,须获取ubuntu的ip而不是使用127.0.0.1,使用ifconfig获取,clientid 可使用Generate
在这里插入图片描述
在Ubuntu终端输入:mosquitto_pub -h 127.0.0.1 -p 1883 -t testtopic -m helloworld来推送消息
同时在mqtt.fx程序中connect并订阅主题testtopic在这里插入图片描述
此时在mqtt.fx中收到消息在这里插入图片描述
再次测试将mqtt.fx作为发布者,将mosquitto代理服务器作为订阅者:
在ubuntu终端键入:mosquitto_sub -h 127.0.0.1 -p 1883 -v -t testtopic
在这里插入图片描述
此时在终端收到消息:

zhanghang@Ubuntu-14:~/MQTT/paho.mqtt.c$ mosquitto_sub  -h 127.0.0.1 -p 1883 -v -t testtopic
testtopic Hi,man,can you see me?

测试结束
参考博客:https://www.jianshu.com/p/d421bb32fe4c
https://blog.csdn.net/xukai871105/article/details/39252653

猜你喜欢

转载自blog.csdn.net/qq_43260665/article/details/88369355