| | |
| | | public void reconnect() { |
| | | while (!mqttClient.isConnected()) { |
| | | try { |
| | | mqttClient.connect(); |
| | | // MQTT的连接设置 |
| | | MqttConnectOptions options = new MqttConnectOptions(); |
| | | options.setUserName(USER_NAME); |
| | | options.setPassword(PASS_WORD.toCharArray()); |
| | | // 设置超时时间 单位为秒 |
| | | options.setConnectionTimeout(TIME_OUT);///默认:30 |
| | | // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,设置为true表示每次连接到服务器都以新的身份连接 |
| | | options.setCleanSession(true);//默认:true |
| | | // 设置断开后重新连接(设置为true时将启用自动重新连接) |
| | | options.setAutomaticReconnect(true);//默认:false |
| | | // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制 |
| | | options.setKeepAliveInterval(KEEP_ALIVE);//默认:60 |
| | | mqttClient.connect(options); |
| | | System.out.println("重连成功"); |
| | | } catch (MqttException e) { |
| | | System.out.println("重连失败"); |
| | | log.info("connectionLost e:{}", e.getMessage()); |
| | | e.printStackTrace(); |
| | | } |
| | | } |