mqtt断开自动重连

mqtt订阅接收数据端断线自动重连,经过多次实测有效,有问题或者有更好的解决办法的欢迎反馈,谢谢。

mqtt相关jar自行搜索下载

web.xml

<!--启动MQTT接收监测-->
<listener>
  <listener-class>com.mqtt.MqttLoadServer</listener-class>
</listener>

监听类

public class MqttLoadServer implements ServletContextListener {
    
    public static MqttReceiveTest mqttReceiveTest =new MqttReceiveTest ();
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("****** MqttReceiveTest stop *******");
        mqttReceiveTest.stop();
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("****** MqttReceiveTest start *******");
        mqttReceiveTest.start();
    }
}

mqtt接收类

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

import java.util.Date;

public class MqttReceiveTest {

    private final String HOST = CommonUtil.HOST;//MQTT服务端IP以及连接端口
    private final String PTOPIC1 = "test/#";//订阅主题

    private String clientid = "testServer";//客户端ID唯一,相同的会被逼下线
    private MqttClient client;
    private MqttConnectOptions options;
    private final String userName = CommonUtil.userName;//MQTT服务端连接账号
    private final String passWord = CommonUtil.passWord;//MQTT服务端连接密码


    public MqttReceiveTest() {
        // host为主机名,clientid即连接MQTT的客户端ID,一般以唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
        try {
            client = new MqttClient(HOST, clientid, new MemoryPersistence());
            // MQTT的连接设置
            options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置连接的用户名
            options.setUserName(userName);
            // 设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            // 设置回调
            client.setCallback(new MqttCallback() {

                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost---------");
                    MqttLoadServer.mqttReceiveTest.stop();//关闭
                    MqttLoadServer.mqttReceiveTest.start();//重新连接
                }

                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("***** get message start *****");
                    System.out.println(new Date());
                    System.out.println("topic:" + topic);
                    System.out.println("Qos:" + message.getQos());
                    System.out.println("message:" + new String(message.getPayload()));
                    System.out.println("***** get message end *****");
                    System.out.println();
                }

                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                try {
                    //判断拦截状态,这里注意一下,如果没有这个判断,是非常坑的
                    if (!client.isConnected()) {
                        System.out.println("***** client to connect *****");
                        client.connect(options);
                    }
                    if (client.isConnected()) {//连接成功,跳出连接
                        System.out.println("***** connect success *****");
                        break;
                    }
                } catch (MqttException e1) {
                    e1.printStackTrace();
                }
            }
            //订阅消息
            client.subscribe(PTOPIC1, 1);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        try {
            // 断开连接
            client.disconnect();
            // 关闭客户端
            client.close();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws MqttException {
        MqttReceiveTest mqttReceiveTest = new MqttReceiveTest();
        mqttReceiveTest.start();
    }
}
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Vue中实现MQTT断开连的方法如下: 1. 首先,安装mqtt库: ```shell npm install mqtt ``` 2. 在main.js中引入mqtt库,并创建一个全局的mqtt实例: ```javascript import mqtt from 'mqtt' // 创建mqtt实例 const mqttClient = mqtt.connect('mqtt://broker.emqx.io') ``` 3. 在Vue的store中定义一个mutation,用于处理MQTT连接和断开: ```javascript // store/index.js import { createStore } from 'vuex' const store = createStore({ state: { mqttConnected: false, mqttClient: null }, mutations: { MQTT_CONNECT(state) { // 连接mqtt state.mqttClient = mqtt.connect('mqtt://broker.emqx.io') state.mqttConnected = true // 监听连接状态 state.mqttClient.on('connect', () => { console.log('MQTT connected') }) // 监听断开连接状态 state.mqttClient.on('close', () => { console.log('MQTT disconnected') state.mqttConnected = false // 断开连接后进行连 setTimeout(() => { state.mqttClient.reconnect() }, 5000) }) }, MQTT_DISCONNECT(state) { // 断开mqtt连接 if (state.mqttClient) { state.mqttClient.end() state.mqttClient = null state.mqttConnected = false } } } }) export default store ``` 4. 在Vue组件中使用mqtt连接和断开: ```vue <template> <div> <!-- 组件内容 --> </div> </template> <script> import { onMounted, defineComponent, onUnmounted } from 'vue' import { useStore } from 'vuex' export default defineComponent({ setup() { const store = useStore() onMounted(() => { // 启动mqtt连接 store.commit('MQTT_CONNECT') }) onUnmounted(() => { // 关闭页面时断开mqtt连接 store.commit('MQTT_DISCONNECT') }) } }) </script> ``` 这样,当页面加载时,会自动连接MQTT,并在断开连接后进行连。在页面销毁时,会断开MQTT连接。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值