MQTT
是机器对机器(M2M
)/物联网(IoT
)连接协议。它被设计为一个极其轻量级的发布/订阅
消息传输协议。对于需要较小代码占用空间和/或网络带宽非常宝贵的远程连接非常有用,是专为受限设备和低带宽、高延迟或不可靠的网络而设计。这些原则也使该协议成为新兴的“机器到机器”(M2M
)或物联网(IoT
)世界的连接设备,以及带宽和电池功率非常高的移动应用的理想选择。例如,它已被用于通过卫星链路与代理通信的传感器、与医疗服务提供者的拨号连接,以及一系列家庭自动化和小型设备场景。它也是移动应用的理想选择,因为它体积小,功耗低,数据包最小,并且可以有效地将信息分配给一个或多个接收器。
特点
- 开放消息协议,简单易实现
- 发布订阅模式,一对多消息发布
- 基于TCP/IP网络连接,提供有序,无损,双向连接。
- 1字节固定报头,2字节心跳报文,最小化传输开销和协议交换,有效减少网络流量。
- 消息QoS支持,可靠传输保证
接下来主要应用于Android中的使用。
1.build.gradle中引入一下包,使项目能正常使用mqtt:
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
2.设置mqtt连接服务器
//连接到服务器public void connectMQTT(String host, String port, String clientId, String userName, String token, IMqttActionListener callBack) {mMqttClient = new MqttAndroidClient(context, String.format("tcp://%s:%s", host, port), clientId);//连接参数MqttConnectOptions options;options = new MqttConnectOptions();//设置自动重连options.setAutomaticReconnect(true);// 缓存options.setCleanSession(true);// 设置超时时间,单位:秒options.setConnectionTimeout(300);// 心跳包发送间隔,单位:秒options.setKeepAliveInterval(45);// 用户名options.setUserName(userName);// 密码options.setPassword(token.toCharArray());options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);// 设置MQTT监听mMqttClient.setCallback(new MqttCallback() {@Overridepublic void connectionLost(Throwable cause) {Log.d(TAG, "connectionLost: 连接断开");mqttListener.onConnectionLost(cause);}@Overridepublic void messageArrived(String topic, MqttMessage message) throws Exception {Log.d(TAG, "收到消息:" + message.toString());mqttListener.onMessageArrived(topic, message);}@Overridepublic void deliveryComplete(IMqttDeliveryToken token) {mqttListener.onDeliveryComplete(token);}});try {if (!mMqttClient.isConnected()) {//进行连接mMqttClient.connect(options, null, callBack);}} catch (MqttException e) {e.printStackTrace();}}
3.订阅主题
public void subscribeMQTT(String topic, int qos, IMqttActionListener callBack) {try {//连接成功后订阅主题mMqttClient.subscribe(topic, qos, null, callBack);} catch (MqttException e) {e.printStackTrace();}}
4.取消订阅主题
public void unsubscribeMQTT(String topic, IMqttActionListener callBack) {try {mMqttClient.unsubscribe(topic, null, callBack);} catch (MqttException e) {e.printStackTrace();}}
5.发送消息
public void sendMsg(String topic, String content, int qos, IMqttActionListener calBack) {MqttMessage msg = new MqttMessage();msg.setPayload(content.getBytes());//设置消息内容msg.setQos(qos);//设置消息发送质量,可为0,1,2.//设置消息的topic,并发送。try {if (mMqttClient.isConnected()) {mMqttClient.publish(topic, msg, null, calBack);}} catch (MqttException e) {e.printStackTrace();}}
6.断开连接
public void disconnect() {if (mMqttClient != null && mMqttClient.isConnected()) {try {mMqttClient.disconnect();} catch (MqttException e) {e.printStackTrace();}}}
7.添加监听事件
public void addMqttListener(MqttListener mqttListener) {this.mqttListener = mqttListener;}public interface MqttListener {void onSendMsgSuccess(IMqttToken asyncActionToken);void onSendMsgFailure(IMqttToken asyncActionToken, Throwable exception);void onConnectionLost(Throwable cause);void onMessageArrived(String topic, MqttMessage message);void onDeliveryComplete(IMqttDeliveryToken token);}
参考文献:MQTT 3.1.1 协议中文版 | MQTT中文网