其他分享
首页 > 其他分享> > Eclipse paho学习笔记

Eclipse paho学习笔记

作者:互联网

Eclipse Paho
java 支持java和android
两个客户端异步和同步, MqttAsyncClient,MqttClient
其中 后者是前者的包装同步器,特效除了5.0都支持
有两个版本可以相互替换


    <dependency>
        <groupId>org.eclipse.paho</groupId>
        <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
        <version>%VERSION%</version>
    </dependency>

 

下面是简单同步的例子:
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 MqttPublishSample {

        public static void main(String[] args) {

            String topic        = "MQTT Examples";
            String content      = "Message from MqttPublishSample";
            int qos             = 2;
            String broker       = "tcp://iot.eclipse.org:1883";
            String clientId     = "JavaSample";
            MemoryPersistence persistence = new MemoryPersistence();

            try {
                MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
                MqttConnectOptions connOpts = new MqttConnectOptions();
                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();
            }
        }
    }
    
    下面是异步处理三个例子
    
    https://github.com/eclipse/paho.mqtt.java/tree/master/org.eclipse.paho.sample.mqttv3app/src/main/java/org/eclipse/paho/sample/mqttv3app
    
    
    最新的java的同步例子有四个类
    
    https://github.com/eclipse/paho.mqtt.java/tree/master/org.eclipse.paho.sample.mqttclient/src/main/java/org/eclipse/paho/sample/mqttclient/mqttv3
    
    发布订阅 连接执行
    执行了4种发布的数据,有文件和消息
    

 

标签:Eclipse,eclipse,System,笔记,println,org,paho,out
来源: https://www.cnblogs.com/genestart/p/11353600.html