[10] MQTT,mosquitto,Eclipse Paho---MQTT消息格式之Publication(消息发布)之QoS==0

在MQTT协议中,消息的发布相对来说比较复杂一些,因为里面牵涉到了QoS(服务质量)和Retained(是否正服务器端存储消息)已经Persistence(当网络故障,在本地客户端存储信息)。其中最为灵活的是QoS的取值,QoS取不同值,就有不同的消息流,也就对应不同了消息类型。首先咱们来讨论QoS等于0的情况。QoS等于0意味着只发送一次,而不管接收方是否收到。

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.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;


import com.test.mqtt.sub.CustomMQTTCallBack;


public class PublicationExample4QoS0 {


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//System.setProperty("java.util.logging.config.file","E:/MQTTWork/ExcelDesignTime/com.tibco.tpcl.mqttpaho/resources/logging.properties");
        String broker = "tcp://192.168.80.196:1883" ;
        String clientId = "paho-1" ;
        MemoryPersistence persistence = new MemoryPersistence();
         try {
                MqttClient sampleClient = new MqttClient(broker, clientId,persistence);
                MqttConnectOptions connOpts = new MqttConnectOptions();
                //connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
                System. out .println("The MQTT Version is:"+connOpts.getMqttVersion());
                connOpts.setCleanSession( false );
                System. out .println( "Connecting to broker: " + broker);
                sampleClient.connect(connOpts);
                System. out .println( "Connected" );
                sampleClient.setCallback(new CustomMQTTCallBack());
                MqttMessage message=new MqttMessage();
                message.setPayload("HelloWorld!".getBytes());
                message.setQos(0);
                message.setRetained(true);
                sampleClient.publish("test",message);
       
        } catch (MqttException me) {
                System. out .println( "reason " + me.getReasonCode());
                System. out .println( "msg " + me.getMessage());
                System. out .println( "loc " + me.getLocalizedMessage());
                System. out .println( "cause " + me.getCause());
                System. out .println( "excep " + me);
                me.printStackTrace();
        }


	}


}


[10] MQTT,mosquitto,Eclipse Paho---MQTT消息格式之Publication(消息发布)之QoS==0_第1张图片



你可能感兴趣的:(MQTT,MQTT)