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();
    }
}
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读