阿里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;
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
连接阿里MQTT需要以下步骤: 1. 在阿里云控制台创建一个MQTT实例,并获取实例的连接信息,包括Broker地址、端口号、用户名和密码等。 2. 在Qt项目中使用paho.mqtt.c库或MQTT-C++库实现MQTT连接,需要在项目中添加对应的头文件和库文件。 3. 在代码中设置MQTT连接参数,包括Broker地址、端口号、用户名和密码等。 4. 实现MQTT回调函数,处理MQTT消息的接收和发送。 以下是一个使用MQTT-C++库连接阿里MQTT的示例代码: ```cpp #include <iostream> #include <mqtt/async_client.h> const std::string SERVER_ADDRESS("tcp://<your-broker-address>:<your-broker-port>"); const std::string CLIENT_ID("<your-client-id>"); const std::string TOPIC("<your-topic>"); const int QOS = 1; class mqtt_callback : public virtual mqtt::callback { public: virtual void connection_lost(const std::string& cause) { std::cout << "Connection lost: " << cause << std::endl; } virtual void message_arrived(mqtt::const_message_ptr msg) { std::cout << "Message arrived: " << msg->get_payload_str() << std::endl; } virtual void delivery_complete(mqtt::delivery_token_ptr token) { std::cout << "Delivery complete for token: " << token->get_message_id() << std::endl; } }; int main(int argc, char* argv[]) { mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID); mqtt::connect_options conn_opts; conn_opts.set_keep_alive_interval(20); conn_opts.set_clean_session(true); conn_opts.set_user_name("<your-username>"); conn_opts.set_password("<your-password>"); mqtt_callback cb; client.set_callback(cb); try { mqtt::token_ptr conntok = client.connect(conn_opts); conntok->wait(); mqtt::token_ptr subtok = client.subscribe(TOPIC, QOS); subtok->wait(); while (true) { mqtt::message_ptr pubmsg = mqtt::make_message(TOPIC, "Hello, world!"); pubmsg->set_qos(QOS); mqtt::token_ptr pubtok = client.publish(pubmsg); pubtok->wait(); } mqtt::token_ptr unsubtok = client.unsubscribe(TOPIC); unsubtok->wait(); mqtt::token_ptr disctok = client.disconnect(); disctok->wait(); } catch (const mqtt::exception& exc) { std::cerr << "MQTT Exception: " << exc.what() << std::endl; return 1; } return 0; } ``` 在这个例子中,我们使用了mqtt::async_client类来创建MQTT连接,设置连接参数并订阅一个主题。在主循环中,我们发送一个消息并等待回复。当程序退出时,我们取消订阅并断开连接。 注意:在实际使用中,需要将<your-broker-address>、<your-broker-port>、<your-client-id>、<your-username>和<your-password>替换为阿里MQTT实例的具体信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值