This commit is contained in:
huangzj
2023-08-03 14:03:46 +08:00
parent ab360ed348
commit 448af492d6
29 changed files with 457 additions and 151 deletions

View File

@@ -0,0 +1,74 @@
package com.njcn.csdevice.utils;
import org.eclipse.paho.client.mqttv3.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Description:
* Date: 2023/8/2 13:41【需求编号】
*
* @author clam
* @version V1.0.0
*/
public class MqttTest {
private static final String MQTT_BROKER = "tcp://192.168.1.13:1883";
private static final String MQTT_TOPIC = "file/upload";
private static final String FILE_PATH = "C:\\Users\\无名\\Desktop\\111.json"; // Replace with the path to your file
public static void main(String[] args) {
MqttClient mqttClient = null;
try {
// Connect to the MQTT broker
mqttClient = new MqttClient(MQTT_BROKER, MqttClient.generateClientId());
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setUserName("t_user");
connOpts.setPassword("njcnpqs".toCharArray());
mqttClient.connect(connOpts);
// Read the file
File file = new File(FILE_PATH);
FileInputStream fis = new FileInputStream(file);
byte[] fileContent = new byte[(int) file.length()];
fis.read(fileContent);
fis.close();
// Create a new MQTT message
MqttMessage message = new MqttMessage(fileContent);
// Set QoS level and retain flag as per your requirement
message.setQos(1);
// message.setRetained(false);
// Record the start time
long startTime = System.currentTimeMillis();
// Publish the message to the MQTT topic
mqttClient.publish(MQTT_TOPIC, message);
// Record the end time
long endTime = System.currentTimeMillis();
System.out.println("File published successfully!");
System.out.println("Time taken: " + (endTime - startTime) + " ms");
} catch (MqttException | IOException e) {
e.printStackTrace();
} finally {
// Disconnect from the MQTT broker
if (mqttClient != null && mqttClient.isConnected()) {
try {
mqttClient.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
}
}