Mosquitto
mosquitto是一款实现了 MQTT v3.1 协议的开源的消息代理服务软件.
其提供了非常轻量级的消息数据传输协议,采用发布/订阅模式进行工作,可用于物联设备、中间件、APP客户端之间的消息通讯。
mosquitto官网
http://mosquitto.org/
关于mqtt协议可参考
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
基础准备
Linux内核版本:Centos 6.5_final_64bit
安装基础软件
yum install gcc-c++ yum install cmake yum install openssl-devel //mosquitto默认支持openssl
下载程序
官网下载
wget http://mosquitto.org/files/source/mosquitto-1.4.4.tar.gztar -xzvf mosquitto-1.4.4.tar.gz cd mosquitto-1.4.4
编译安装
编译选项
当前的程序目录可直接编译,在编译之前需根据需要做一定的配置,否则会出现 xxx.h找不到的情况。
vim config.mk
config.mk包括了多个选项, 可按需关闭或开启,但一旦开启则需要先安装对应的模块
模块说明
选项
|
说明
|
make出错信息
|
WITH_SRV
| 启用c-areas库的支持,一个支持异步DNS查找的库 见http://c-ares.haxx.se |
missing ares.h
|
WITH_UUID
|
启用lib-uuid支持,支持为每个连接的客户端生成唯一的uuid
|
missing uuid.h
|
WITH_WEBSOCKETS
| 启用websocket支持,需安装libwebsockets 对于需要使用websocket协议的应用开启 |
missing libwebsockets.h
|
安装c-areas
安装lib-uuid
yum install libuuid-devel
安装libwebsockets
//若遇到以上模块无法安装的情况,可将对应模块选项关闭即可,但相应功能也将无法提供;
开始安装mosquitto
makemake install
至此程序已经安装完毕!
程序文件将默认安装到以下位置
路径 | 程序文件 |
/usr/local/sbin | mosquiotto server |
/etc/mosquitto | configuration |
/usr/local/bin | utility command |
修正链接库路径
由于操作系统版本及架构原因,很容易出现安装之后的链接库无法被找到,如启动mosquitto客户端可能出现找不到
libmosquitto.so.1文件,因此需要添加链接库路径
启动与测试
创建用户
mosquitto默认以mosquitto用户启动,可以通过配置文件修改
groupadd mosquitto
useradd -g mosuqitto mosquiotto
程序配置
mv /etc/mosquitto/mosquitto.conf.example /etc/mosquitto/mosquitto.conf
配置项说明
//关于详细配置可参考
http://mosquitto.org/man/mosquitto-conf-5.html
启动
mosquitto -c /etc/mosquitto/mosquitto.conf -d
成功将启动1883端口监听
客户端测试
新建两个shell端口A/B
A 订阅主题:
mosquitto_sub -t location
B 推送消息:
mosquitto_pub -t location -h localhost -m "new location"
可以在A窗口看到由B推送的消息,此外服务端窗口也可以看到客户端连接和端口的日志
1443083396: New client connected from 127.0.0.1 as mosqpub/31924-iZ94eb8yq (c1, k60). 1443083396: Client mosqpub/31924-iZ94eb8yq disconnected.、
FAQ
启动mosquitto报错
error while loading shared libraries: libwebsockets.so.4.0.0: cannot open shared object file: No such file or directory
或者
error while loading shared libraries: libmosquitto.so.1: cannot open shared object file: No such file or directory
解决方法
找不到链接库,通过locate或find命令找到libwebsockets.so.4.0.0,将其目录添加至ldconfg配置中:
vim /etc/ld.so.conf.d/liblocal.conf /usr/local/lib64 /usr/local/lib ldconfig //执行ln -s 添加软连接的方式也可行
编译找不到openssl/ssl.h
解决方法
yum install openssl-devel
编译报错
mosquitto.c:871: error: ‘struct mosquitto’ has no member named ‘achan’
找不到areas.h
解决方法
安装 c-areas模块(见上文)或将config.mk中WITH_SRV选项关闭
make test 提示不支持协议
Address family not supported by protocol
一般是指所访问的地址类型不被支持,比如IPV6,忽略该错误即可
服务端:
package com.mysite.erp.pay.service
;
import org.eclipse.paho.client.mqttv3.* ;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence ;
/**
* @author 105
* @version 2.0.4
* @desc:
* @Created by ${Spring} on 2018/3/26.
*/
public class ServerMQTT {
//tcp://MQTT安装的服务器地址:MQTT定义的端口号
public static final String HOST = "tcp://120.78.76.48:1883" ;
//定义一个主题
public static final String TOPIC = "topic11" ;
//定义MQTT的ID,可以在MQTT服务配置中指定
private static final String clientid = "server11" ;
private MqttClient client ;
private MqttTopic topic11 ;
private String userName = "mosquitto" ;
private String passWord = "" ;
private MqttMessage message ;
/**
* 构造函数
* @throws MqttException
*/
public ServerMQTT() throws MqttException {
// MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient( HOST , clientid , new MemoryPersistence()) ;
connect() ;
}
/**
* 用来连接服务器
*/
private void connect() {
MqttConnectOptions options = new MqttConnectOptions() ;
options.setCleanSession( false) ;
options.setUserName( userName) ;
options.setPassword( passWord.toCharArray()) ;
// 设置超时时间
options.setConnectionTimeout( 10) ;
// 设置会话心跳时间
options.setKeepAliveInterval( 20) ;
try {
client.setCallback( new PushCallback()) ;
client.connect(options) ;
topic11 = client.getTopic( TOPIC) ;
} catch (Exception e) {
e.printStackTrace() ;
}
}
/**
*
* @param topic
* @param message
* @throws MqttPersistenceException
* @throws MqttException
*/
public void publish(MqttTopic topic , MqttMessage message) throws MqttPersistenceException ,
MqttException {
MqttDeliveryToken token = topic.publish(message) ;
token.waitForCompletion() ;
System. out.println( "message is published completely! "+ token.isComplete()) ;
}
/**
* 启动入口
* @param args
* @throws MqttException
*/
public static void main(String[] args) throws MqttException {
ServerMQTT server = new ServerMQTT() ;
server. message = new MqttMessage() ;
server. message.setQos( 1) ;
server. message.setRetained( true) ;
server. message.setPayload( "hello,topic11".getBytes()) ;
server.publish(server. topic11 , server. message) ;
System. out.println(server. message.isRetained() + "------ratained状态") ;
}
}
import org.eclipse.paho.client.mqttv3.* ;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence ;
/**
* @author 105
* @version 2.0.4
* @desc:
* @Created by ${Spring} on 2018/3/26.
*/
public class ServerMQTT {
//tcp://MQTT安装的服务器地址:MQTT定义的端口号
public static final String HOST = "tcp://120.78.76.48:1883" ;
//定义一个主题
public static final String TOPIC = "topic11" ;
//定义MQTT的ID,可以在MQTT服务配置中指定
private static final String clientid = "server11" ;
private MqttClient client ;
private MqttTopic topic11 ;
private String userName = "mosquitto" ;
private String passWord = "" ;
private MqttMessage message ;
/**
* 构造函数
* @throws MqttException
*/
public ServerMQTT() throws MqttException {
// MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient( HOST , clientid , new MemoryPersistence()) ;
connect() ;
}
/**
* 用来连接服务器
*/
private void connect() {
MqttConnectOptions options = new MqttConnectOptions() ;
options.setCleanSession( false) ;
options.setUserName( userName) ;
options.setPassword( passWord.toCharArray()) ;
// 设置超时时间
options.setConnectionTimeout( 10) ;
// 设置会话心跳时间
options.setKeepAliveInterval( 20) ;
try {
client.setCallback( new PushCallback()) ;
client.connect(options) ;
topic11 = client.getTopic( TOPIC) ;
} catch (Exception e) {
e.printStackTrace() ;
}
}
/**
*
* @param topic
* @param message
* @throws MqttPersistenceException
* @throws MqttException
*/
public void publish(MqttTopic topic , MqttMessage message) throws MqttPersistenceException ,
MqttException {
MqttDeliveryToken token = topic.publish(message) ;
token.waitForCompletion() ;
System. out.println( "message is published completely! "+ token.isComplete()) ;
}
/**
* 启动入口
* @param args
* @throws MqttException
*/
public static void main(String[] args) throws MqttException {
ServerMQTT server = new ServerMQTT() ;
server. message = new MqttMessage() ;
server. message.setQos( 1) ;
server. message.setRetained( true) ;
server. message.setPayload( "hello,topic11".getBytes()) ;
server.publish(server. topic11 , server. message) ;
System. out.println(server. message.isRetained() + "------ratained状态") ;
}
}
客户端:
package com.mysite.erp.pay.service
;
import org.eclipse.paho.client.mqttv3.MqttClient ;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions ;
import org.eclipse.paho.client.mqttv3.MqttException ;
import org.eclipse.paho.client.mqttv3.MqttTopic ;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence ;
import java.util.concurrent.ScheduledExecutorService ;
/**
* @author 105
* @version 2.0.4
* @desc:
* @Created by ${Spring} on 2018/3/26.
*/
public class ClientMQTT {
public static final String HOST = "tcp://120.78.76.48:1883" ;
public static final String TOPIC = "topic11" ;
private static final String clientid = "client11" ;
private MqttClient client ;
private MqttConnectOptions options ;
private String userName = "admin" ;
private String passWord = "password" ;
private ScheduledExecutorService scheduler ;
private void start() {
try {
// host为主机名,clientid即连接MQTT的客户端ID,一般以唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient( HOST , clientid , new MemoryPersistence()) ;
// MQTT的连接设置
options = new MqttConnectOptions() ;
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession( true) ;
// 设置连接的用户名
options.setUserName( userName) ;
// 设置连接的密码
options.setPassword( passWord.toCharArray()) ;
// 设置超时时间 单位为秒
options.setConnectionTimeout( 10) ;
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
options.setKeepAliveInterval( 20) ;
// 设置回调
client.setCallback( new PushCallback()) ;
MqttTopic topic = client.getTopic( TOPIC) ;
//setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
options.setWill(topic , "close".getBytes() , 2 , true) ;
client.connect( options) ;
//订阅消息
int[] Qos = { 1} ;
String[] topic1 = { TOPIC} ;
client.subscribe(topic1 , Qos) ;
} catch (Exception e) {
e.printStackTrace() ;
}
}
public static void main(String[] args) throws MqttException {
ClientMQTT client = new ClientMQTT() ;
client.start() ;
}
import org.eclipse.paho.client.mqttv3.MqttClient ;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions ;
import org.eclipse.paho.client.mqttv3.MqttException ;
import org.eclipse.paho.client.mqttv3.MqttTopic ;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence ;
import java.util.concurrent.ScheduledExecutorService ;
/**
* @author 105
* @version 2.0.4
* @desc:
* @Created by ${Spring} on 2018/3/26.
*/
public class ClientMQTT {
public static final String HOST = "tcp://120.78.76.48:1883" ;
public static final String TOPIC = "topic11" ;
private static final String clientid = "client11" ;
private MqttClient client ;
private MqttConnectOptions options ;
private String userName = "admin" ;
private String passWord = "password" ;
private ScheduledExecutorService scheduler ;
private void start() {
try {
// host为主机名,clientid即连接MQTT的客户端ID,一般以唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient( HOST , clientid , new MemoryPersistence()) ;
// MQTT的连接设置
options = new MqttConnectOptions() ;
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession( true) ;
// 设置连接的用户名
options.setUserName( userName) ;
// 设置连接的密码
options.setPassword( passWord.toCharArray()) ;
// 设置超时时间 单位为秒
options.setConnectionTimeout( 10) ;
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
options.setKeepAliveInterval( 20) ;
// 设置回调
client.setCallback( new PushCallback()) ;
MqttTopic topic = client.getTopic( TOPIC) ;
//setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
options.setWill(topic , "close".getBytes() , 2 , true) ;
client.connect( options) ;
//订阅消息
int[] Qos = { 1} ;
String[] topic1 = { TOPIC} ;
client.subscribe(topic1 , Qos) ;
} catch (Exception e) {
e.printStackTrace() ;
}
}
public static void main(String[] args) throws MqttException {
ClientMQTT client = new ClientMQTT() ;
client.start() ;
}
}
回执
package com.mysite.erp.pay.service
;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken ;
import org.eclipse.paho.client.mqttv3.MqttCallback ;
import org.eclipse.paho.client.mqttv3.MqttMessage ;
/**
* @author 105
* @version 2.0.4
* @desc:
* @Created by ${Spring} on 2018/3/26.
*/
public class PushCallback implements MqttCallback {
@Override
public void connectionLost(Throwable cause) {
// 连接丢失后,一般在这里面进行重连
System. out.println( "连接断开,可以做重连") ;
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
System. out.println( "deliveryComplete---------" + token.isComplete()) ;
}
@Override
public void messageArrived(String topic , MqttMessage message) throws Exception {
// subscribe后得到的消息会执行到这里面
System. out.println( "接收消息主题 : " + topic) ;
System. out.println( "接收消息Qos : " + message.getQos()) ;
System. out.println( "接收消息内容 : " + new String(message.getPayload())) ;
}
}
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken ;
import org.eclipse.paho.client.mqttv3.MqttCallback ;
import org.eclipse.paho.client.mqttv3.MqttMessage ;
/**
* @author 105
* @version 2.0.4
* @desc:
* @Created by ${Spring} on 2018/3/26.
*/
public class PushCallback implements MqttCallback {
@Override
public void connectionLost(Throwable cause) {
// 连接丢失后,一般在这里面进行重连
System. out.println( "连接断开,可以做重连") ;
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
System. out.println( "deliveryComplete---------" + token.isComplete()) ;
}
@Override
public void messageArrived(String topic , MqttMessage message) throws Exception {
// subscribe后得到的消息会执行到这里面
System. out.println( "接收消息主题 : " + topic) ;
System. out.println( "接收消息Qos : " + message.getQos()) ;
System. out.println( "接收消息内容 : " + new String(message.getPayload())) ;
}
}
原文地址:https://www.cnblogs.com/littleatp/p/4835879.html