java的mqtt生产者和消费者的代码
以下是一个简单的Java MQTT消息队列生产者和消费者的示例代码。
生产者(Publisher):
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
public class MQTTPublisher {
private static final String BROKER_URL = "tcp://localhost:1883";
private static final String CLIENT_ID = "JavaPublisher";
private static final String TOPIC = "sampleTopic";
public static void main(String[] args) {
try {
MqttClient sampleClient = new MqttClient(BROKER_URL, CLIENT_ID);
sampleClient.connect();
String message = "Hello, MQTT!";
MqttMessage messageObj = new MqttMessage(message.getBytes());
sampleClient.publish(TOPIC, messageObj);
System.out.println("Message published");
sampleClient.disconnect();
System.out.println("Disconnected");
System.exit(0);
} catch (MqttPersistenceException | MqttException me) {
System.out.println("Exception: " + me.getMessage());
}
}
}
消费者(Subscriber):
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.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class MQTTSubscriber implements MqttCallback {
private static final String BROKER_URL = "tcp://localhost:1883";
private static final String CLIENT_ID = "JavaSubscriber";
private static final String TOPIC = "sampleTopic";
private MqttClient client;
public MQTTSubscriber() throws MqttException {
client = new MqttClient(BROKER_URL, CLIENT_ID);
client.setCallback(this);
client.connect();
client.subscribe(TOPIC);
System.out.println("Subscribed to " + TOPIC);
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Message received: " + new String(message.getPayload()));
}
public void connectionLost(Throwable cause) {
System.out.println("Connection lost");
评论已关闭