[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();
        }


	}


}





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值