mqtt java demo

    本文地址:http://tongxinmao.com/Article/Detail/id/171

    package com.tongxinmao.mqtt;
     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;
    
    public class mqttcli {
    
    public static void main(String[] args) {
    
        String topic        = "/publish/TEST/javademo";
        String content      = "Message from MqttPublishSample";
        int qos             = 2;
        String broker       = "tcp://mq.tongxinmao.com:18831";
        String clientId     = "javademo";
        MemoryPersistence persistence = new MemoryPersistence();
    
        try {
            MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName("TEST");
            connOpts.setPassword("TEST".toCharArray());
            connOpts.setCleanSession(true);
            System.out.println("Connecting to broker: "+broker);
            sampleClient.connect(connOpts);
            System.out.println("Connected");
            System.out.println("Publishing message: "+content);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            sampleClient.publish(topic, message);
            System.out.println("Message published");
            sampleClient.disconnect();
            System.out.println("Disconnected");
            System.exit(0);
        } 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();
        }
    }
    }



    http://www.eclipse.org/paho/downloads.php


    上一篇:公共MQTT服务器
    下一篇:部分手机LOGCAT无输出解决办法