client2.java 2.33 KB
package com.huaheng.framework.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class client2 {

    //连接地址
    public static final String HOST = "tcp://47.100.176.190:1883";
    //订阅的话题
    public static final String TOPIC = "18761185821onlineInform";
    //客户端ID 全球唯一,建议使用UUID生成
    private static final String clientid = "client124";
    private MqttClient client;
    private MqttConnectOptions options;
    private String userName = "admin";
    private String passWord = "admin";

    public void start() {
        try {
            // MemoryPersistence设置clientid的保存形式,默认为以内存保存
            client=new MqttClient(HOST, clientid,new MemoryPersistence());
            //连接设置
            options=new MqttConnectOptions();
            //清除会话
            options.setCleanSession(false);
            //用户名密码   密码类型是char数组
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            //超时时间
            options.setConnectionTimeout(10);
            //心跳
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(mqttCallback);
            //主题类
            MqttTopic topic=client.getTopic(TOPIC);
            //遗嘱设置
            options.setWill(topic, "close".getBytes(), 2, true);
            client.connect(options);
            //订阅主题   qos为订阅主题的下标的消息服务质量
            int[] Qos  = {1};
            String[] topic1 = {TOPIC};
            client.subscribe(topic1, Qos);
        } catch (MqttException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        client2 client2=new client2();
        client2.start();
    }

    MqttCallback mqttCallback = new MqttCallback() {
        @Override
        public void connectionLost(Throwable throwable) {

        }

        @Override
        public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {

        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

        }
    };
}