阿里MQTT连接

import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;


import org.apache.commons.codec.binary.Base64;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
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.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class MqttConnect {
    private static final String TAG= "MQTT";
    private String clientId ="";//GROUPID@@@自定义
    private static MqttClient client;//client
    private MqttConnectOptions options;//配置
    private static MqttConnect instance;
    public static MqttConnect getInstance() {
        if (null == instance) {
            synchronized (MqttConnect.class) {
                instance = new MqttConnect();
            }
        }
        return instance;
    }

    public MqttConnect() {
        try {
           MqttInit();
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
        MqttConnectThread mqttConnectThread = new MqttConnectThread();
        mqttConnectThread.start();//连接服务器任务
    }

    private void MqttInit() throws NoSuchAlgorithmException, InvalidKeyException {
        clientId =  clientId + "";
        try
        {
            //(1)主机地址(2)客户端ID,一般以客户端唯一标识符(不能够和其它客户端重名)(3)内存保留client
            client = new MqttClient("tcp:xxx:1883", clientId,new MemoryPersistence());
        } catch (MqttException e) {
            e.printStackTrace();
        }
        options = new MqttConnectOptions();//MQTT的连接设置
        options.setCleanSession(false);//设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
        options.setUserName("");//设置连接的用户名(自己的服务器没有设置用户名)
        String s = macSignature(clientId, "");
        options.setPassword(s.toCharArray());//设置连接的密码
        options.setConnectionTimeout(30);//  设置连接超时时间 单位为秒
        options.setKeepAliveInterval(20);// 设置会话心跳时间 单位为秒
        options.setAutomaticReconnect(true); //设置重连机制
        client.setCallback(new MqttCallback() {
            @Override//获取消息会执行这里--arg0是主题,arg1是消息
            public void messageArrived(final String arg0, MqttMessage arg1) throws Exception {
                final String topic = arg0;//主题
                final String msgString  = new String(arg1.getPayload(),"GBK");
                Log.e(TAG,topic);
                Log.e(TAG,msgString);
               
            }
            @Override//订阅主题后会执行到这里
            public void deliveryComplete(IMqttDeliveryToken arg0) {
                Log.e(TAG,"deliveryComplete");
            }
            @Override//连接丢失后,会执行这里
            public void connectionLost(Throwable arg0) {
                Log.e(TAG,"connectionLost");

            }
        });
    }

    /*连接服务器任务*/
    class MqttConnectThread extends Thread {
        public void run() {
            try {
                client.connect(options);
                client.subscribe("test/"+T.getDeviceNo(), 1);//设置(订阅)接收的主题,主题的级别是1
                Log.e(TAG, " connetecd " + client.isConnected());
            } catch (MqttSecurityException e) {
                //安全问题连接失败
                Log.e(TAG, "a" + e.toString());
            } catch (MqttException e) {
                //连接失败原因
                Log.e(TAG, e.toString());

            }
        }
    }
    /**
     * @param text 要签名的文本
     * @param secretKey 阿里云MQ secretKey
     * @return 加密后的字符串
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     */
    public static String macSignature(String text,
                                      String secretKey) throws InvalidKeyException, NoSuchAlgorithmException {
        Charset charset = Charset.forName("UTF-8");
        String algorithm = "HmacSHA1";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(secretKey.getBytes(charset), algorithm));
        byte[] bytes = mac.doFinal(text.getBytes(charset));
        return new String(Base64.encodeBase64(bytes), charset);
    }

    public void clearClient() {
        if (client !=null) {
            try {
                client.disconnect();
                client = null;
            } catch (MqttException e) {
                e.printStackTrace();
            }
            instance = null;
            options = null;
        }
    }

}

你可能感兴趣的:(MQTT)