Message MQTT not receive in subscribe client - java

I'm working on MQTT protocol and I try to publish and subscribe with 2 distincts Java applications.
My first application is "Publish". I'm publish on a MQTT server a message.
My second application is "Subscribe". I'm subscribe to a topic and try to receive the message. But I never receive the message.
When I run the 2 applications, I begin with the "Subscribe" application and after I run the "Publish" application. When the "Publish" application begin, I lose my connection to the "Subscribe" application and I can't receive my message.
In the "Subscribe" application, my method messageArrived() is never called by client.setCallback(this). (See the code below).
Here is my 2 code application :
Publish Application :
Class PubClient :
package publishclient;
import java.util.Random;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class PubClient implements MqttCallback {
MqttClient client;
MqttConnectOptions connOpt;
Random rand = new Random();
int nbRandom = 0;
int valMax =151, valMin = 40;
public PubClient() throws MqttException {
String broker = "tcp://88.177.147.17:1883"; // Adress MQTT Server
String clientId = "0bdd-4445-82f3-928f8ddb1887"; // ClientID
String topic1f = "ApplicationRio/capteur"; // Topic
int QoSserveur = 2;
try {
String uuid = "ac8da3c6-0bdd-4445-82f3-928f8ddb3294";
MemoryPersistence persistence = new MemoryPersistence();
// Create 2 objects : client and connOpt
client = new MqttClient(broker, clientId, persistence);
connOpt = new MqttConnectOptions();
connOpt.setCleanSession(true);
client.setCallback(this);
// Connection to MQTT server
System.out.println("Connexion a : " + broker + " Publisher");
client.connect(connOpt);
//Create random number for my message
nbRandom = valMin + rand.nextInt(valMax-valMin);
System.out.println("nb aleatoire = " + nbRandom);
String messageAEnvoyer = uuid + "//" + nbRandom;
System.out.println("Message a envoyer : " + messageAEnvoyer);
MqttMessage message = new MqttMessage();
message.setPayload(messageAEnvoyer.getBytes());
message.setQos(QoSserveur);
client.publish(topic1f, message);
} catch(MqttException e) {
e.printStackTrace();
}
}
#Override
public void connectionLost(Throwable thrwbl) {System.out.println("Perdue connexion");}
#Override
public void messageArrived(String string, MqttMessage mm) throws Exception {
System.out.println("Message recu est : "+ new String(mm.getPayload()));}
#Override
public void deliveryComplete(IMqttDeliveryToken imdt) {
System.out.println("Message delivre au broker");
}
}
The main (Publish) :
package publishclient;
import org.eclipse.paho.client.mqttv3.MqttException;
public class PublishClient {
public static void main(String[] args) throws MqttException {
PubClient publieur = new PubClient();
}
The "subscribe" application :
Class SubClient :
package subscribeclient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
public class SubClient implements MqttCallback {
MqttClient clientsub;
MqttConnectOptions connOpt;
public SubClient() throws MqttException{
String broker = "tcp://88.177.147.17:1883"; // Adress MQTT Server
String clientId = "0bdd-4445-82f3-928f8ddb1887"; // ClientID
String topic1f = "ApplicationRio/capteur"; // Topic
int QoSserveur = 2;
try{
// Create 2 objects : client and connOpt
clientsub = new MqttClient(broker, clientId);
connOpt = new MqttConnectOptions();
connOpt.setCleanSession(false);
connOpt.setKeepAliveInterval(30);
clientsub.setCallback(this);
// Connection to MQTT Server
System.out.println("Connexion a : " + broker + " Subscriber");
clientsub.connect(connOpt);
clientsub.subscribe(topic1f,QoSserveur);
} catch(MqttException e){
e.printStackTrace();
}
}
#Override
public void connectionLost(Throwable thrwbl) {
System.out.println("Connexion perdue");
}
#Override
public void messageArrived(String string, MqttMessage message) throws Exception {
System.out.println("Le message recu est : " + new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken imdt) {
System.out.println("Message arrive");
}
}
The main (Subscribe) :
package subscribeclient;
import org.eclipse.paho.client.mqttv3.MqttException;
public class SubscribeClient {
public static void main(String[] args) throws MqttException {
SubClient subscriber = new SubClient();
}
}
My 2 applications need to run in the same time, and I don't need to disconnect because I run applications all the time.
So, have you got an idea of why my "Subscribe Client" disconnect when I run the "Publish Client" and why I can't receive my message on my "Subscribe Message" ?
I use org.eclipse.paho.client.mqttv3-1.0.2.jar for the library for MQTT.

Client IDs have to be unique between ALL clients. You have used the same client ID for the publisher and subscriber so the broker will kick the subscriber off when the publisher connects.

Related

ActiveMQConnectionFactory - trusted packages not taken into account

I have an active MQ factory in a Spring Boot app, type ActiveMQConnectionFactory.
Right after instantiating it I set the trusted packages to just java.lang since I want to be able to send/receive just Strings via JMS in my app.
See also here:
SpringBoot + ActiveMQ - How to set trusted packages?
https://stackoverflow.com/a/36622567/2300597
#Bean(name="jmsConnectionFactory")
public ConnectionFactory getJMSConnectionFactory(){
_factory = new ActiveMQConnectionFactory(active_MQ_BrokerURL);
ActiveMQConnectionFactory fct = ((ActiveMQConnectionFactory)_factory);
fct.setTrustAllPackages(false);
fct.setTrustedPackages(Arrays.asList("java.lang"));
return _factory;
}
And yet I am able to send other objects (not from package java.lang)?!
I don't get an Exception of some sort when sending them.
Why is that? What am I doing wrong?
NOTE: I am using org.springframework.jms.core.JmsTemplate to send the messages
(in case that matters). The template is linked to that factory.
public void sendObjectMessage(final Serializable msg) {
try {
this.jmsTemplate.send(this.queue, new MessageCreator() {
public Message createMessage(final Session session) throws JMSException {
return session.createObjectMessage(msg);
}
});
logger.info("Success sending Object MQ message [{}]", msg);
} catch (Exception e) {
logger.error("Error sending Object MQ message [{}]", msg, e);
}
}
You can run the code below to validate that it is not an ActiveMQ issue.
What is the consumer side of your code?
How are you confirming messages are not sent?
There is a candidate if the messages are not being received-- if Spring JMS is using the JMS 2.0 API jar, there is a new API call for ObjectMessage that could be bombing out under the covers.
import java.io.Serializable;
import java.util.Arrays;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
public class JmsUrlTest {
private static String brokerUrl = "tcp://localhost:61616";
private static ActiveMQConnectionFactory activemqConnectionFactory = new ActiveMQConnectionFactory("admin", "admin", brokerUrl);
public static void main(String[] args) {
try {
activemqConnectionFactory.setTrustedPackages(Arrays.asList("java.lang"));
Connection connection = activemqConnectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(session.createQueue("OBJECT.TEST"));
Message message = session.createObjectMessage(new String("Test object"));
message.setJMSType("java.lang.String");
messageProducer.send(message);
System.out.println("Sent message " + message.getJMSMessageID());
MessageConsumer messageConsumer = session.createConsumer(session.createQueue("OBJECT.TEST"));
boolean stop = false;
int loopCount = 0;
int maxLoops = 10;
Message recvMessage = null;
do {
recvMessage = messageConsumer.receive(2000l);
if(recvMessage != null || loopCount >= maxLoops) {
stop = true;
}
} while (!stop);
if(recvMessage != null && ObjectMessage.class.isAssignableFrom(recvMessage.getClass())) {
ObjectMessage recvObjectMessage = ObjectMessage.class.cast(recvMessage);
Serializable recvSerializableBody = recvObjectMessage.getObject();
if(recvSerializableBody.getClass().isAssignableFrom(String.class)) {
System.out.println("Recieved ObjectMessage w/ String body: " + String.class.cast(recvSerializableBody));
} else {
System.out.println("Received body was not a String.class");
}
} else {
System.out.println("No message received");
}
} catch (JMSException e) {
e.printStackTrace();
} finally {
}
}
}

How do I make a java app communicate with an ESP32 board?

I've been trying to establish a TCP socket connection between an ESP32 board and a Java server. After establishing the connection, I want the server to send a packet to the ESP32 to request its ID (I use the ID to identify the clients, as there are going to be more of them), but the server doesn't seem to be transmitting anything (ESP32 isn't receiving anything). I even tried using Wireshark to track the packets, but upon connection, there is no message to be seen. Sorry for the horrible code, I'm still a beginner, when it comes to communication programming. Thanks in advance for your help.
Here is the code for the ESP32:
#include <WiFi.h>
WiFiClient client;
// network info
char *ssid = "SSID";
char *pass = "Password";
// wifi stats
int wifiStatus;
int connAttempts = 0;
// Client ID
int id = 128;
IPAddress server(192,168,1,14);
int port = 3241;
String inData;
void setup() {
Serial.begin(115200); // for debug
// attempting to connect to the network
wifiStatus = WiFi.begin(ssid, pass);
while(wifiStatus != WL_CONNECTED){
Serial.print("Attempting to connect to the network, attempt: ");
Serial.println(connAttempts++);
wifiStatus = WiFi.begin(ssid, pass);
delay(1000);
}
// info
Serial.print("Connected to the network, IP address is: '");
Serial.print(WiFi.localIP());
Serial.print("', that took ");
Serial.print(connAttempts);
Serial.println(" attempt(s).");
connAttempts = 0;
// connection to the main server
Serial.println("Starting connection to the server...");
while(!client.connect(server, port)){
Serial.print("Attempting connection to the server, attempt no. ");
Serial.println(connAttempts++);
delay(1000);
}
Serial.print("Connection successful after ");
Serial.print(connAttempts);
Serial.println(" attempt(s)!");
}
void loop() {
if(client.available()){
Serial.println("Incoming data!");
inData = client.readString();
}
if(inData != ""){
Serial.print("Incoming data: ");
Serial.println(inData);
if(inData == "REQ_ID"){
String msg = "INTRODUCTION;"
strcat(msg, m);
client.print(msg);
}
inData = "";
}
if(!client.connected()){
Serial.println("Lost connection to the server! Reconnecting...");
connAttempts = 0;
while(!client.connect(server, port)){
Serial.print("Attempting connection to the server, attempt no. ");
Serial.println(connAttempts++);
delay(1000);
}
Serial.print("Reconnection successful after ");
Serial.print(connAttempts);
Serial.println(" attempt(s)!");
}
delay(10);
}
And here is the client handler class from the Java server:
package org.elektrio.vsd2020;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
public class ClientHandler implements Runnable {
public Socket netSocket;
public BufferedInputStream in;
public BufferedOutputStream out;
private int clientID;
public ClientHandler(Socket skt) throws IOException {
this.netSocket = skt;
this.in = new BufferedInputStream(this.netSocket.getInputStream());
this.out = new BufferedOutputStream(this.netSocket.getOutputStream());
}
public void close() throws IOException{
this.in.close();
this.out.close();
this.netSocket.close();
}
#Override
public void run() {
while(netSocket.isConnected()){
try{
byte[] arr = new byte[2048];
in.read(arr);
String[] input = new String(arr, StandardCharsets.US_ASCII).split(";");
// if the message is tagged as "INTRODUCTION", it identifies a reply from the ESP32, which contains the client ID
if(input[0].equals("INTRODUCTION")){
clientID = Integer.parseInt(input[1]);
}
}
catch (IOException e) {
System.out.println("[" + LocalDateTime.now() + " at ClientHandler] Exception at client ID '" + clientID + "'!");
e.printStackTrace();
}
}
System.out.println("[" + LocalDateTime.now() + " at ClientHandler] Client ID '" + clientID + "' disconnected!");
Tools.clients.remove(this);
}
public int getID(){
return clientID;
}
public int reqID() throws IOException{
String req = "REQ_ID";
out.write(req.getBytes(StandardCharsets.US_ASCII));
}
}
Server's main class:
package org.elektrio.vsd2020;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static ServerSocket server;
public static ServerSocket remoteAccessServer;
public static ExecutorService pool;
public static boolean serviceRunning = true;
public static void main(String[] args) {
try{
// startup args
int port = args.length > 0 ? Integer.parseInt(args[0]) : 3241;
int maxClients = args.length > 1 ? Integer.parseInt(args[2]) : 10;
// startup parameters info
Tools.log("Main", "Server started with parameters: ");
if(args.length > 0) Tools.log("Main", args);
else Tools.log("Main", "Default parameters");
// server socket and the threadpool, where the client threads get executed
server = new ServerSocket(port);
pool = Executors.newFixedThreadPool(maxClients);
// main loop
while(true){
if(Tools.clients.size() < maxClients){
// connection establishment
Socket clientSocket = server.accept();
ClientHandler client = new ClientHandler(clientSocket);
Tools.log("Main", "New client connected from " + clientSocket.getRemoteSocketAddress());
// starting the client operation
pool.execute(client);
Tools.clients.add(client);
Thread.sleep(500);
client.reqID();
}
}
}
catch (IOException | InterruptedException ioe){
Tools.log("Main", "IOException at MAIN");
ioe.printStackTrace();
}
}
}
And lastly, the Tools class
package org.elektrio.vsd2020;
import java.time.LocalDateTime;
import java.util.ArrayList;
public class Tools {
public static ArrayList<ClientHandler> clients = new ArrayList<>();
public static void log(String origin, String message){
System.out.println("[" + LocalDateTime.now() + " at " + origin + "] " + message);
}
public static void log(String origin, String[] messages){
for(String msg : messages) System.out.println("[" + LocalDateTime.now() + " at " + origin + "] " + msg);
}
}
I have some recommendations:
I- Your server implementation, i.e. while(true){... Thread.sleep(500); ... }, resembles microcontroller-style programming. Java has much more powerful tools for socket communication, such as reactive frameworks. I suggest using frameworks like Netty:
Netty 4 User Guide
Introduction to Netty
It may require some effort to learn these but their performance is much better.
And also there exists modern protocols for IoT systems, like MQTT or even RSocket. You can use them instead of plain TCP connection.
II: In IoT systems, isolating the problem is very important. So in your case, using TCP terminal tools like Hercules helps a lot. These tools can act as both server and client; so you can use them instead of ESP32 and Java Server and test if the other side works well.
III: In IoT communications, try to limit the messages. Thus Instead of this conversion between ESP32 and Java:
ESP32: Hi
Java: Hello, who are you?
. My ID is ...
. Pass me the data...
. Here is the data...
Use this:
ESP32: Hi. I am ID .. and This is my data
Server: OK Thanks!

Class Not-Found exception while running subscriber of Paho Client MQTT

I am trying to implement Pub-Sub using packages in org.eclipse.paho.client.mqttv3-1.2.0.jar
Below int the Subscriber Code:
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import java.net.*;
public class Subscriber {
//public static final String BROKER_URL = "tcp://iot.eclipse.org:1883";
public static final String BROKER_URL = "tcp://localhost:1883";
private MqttClient client;
String topic = "Demo Topic";
public static void main(String[] args) {
System.out.println("MQTT Broker: " + BROKER_URL);
new Subscriber();
}
public Subscriber() {
String clientId = getMacAddress() + "-sub";
System.out.println("Client ID = " + clientId);
try {
client = new MqttClient(BROKER_URL, clientId);
client.connect();
client.setCallback(new SubscribeCallback());
client.subscribe(topic);
} catch (MqttException e) {
e.printStackTrace(); System.exit(1);
}
}
public byte[] getMacAddress(){
byte[] mac = new byte[6];
try{
InetAddress address = InetAddress.getLocalHost();
NetworkInterface nwi = NetworkInterface.getByInetAddress(address);
mac = nwi.getHardwareAddress();
System.out.println(mac);
} catch(Exception e) {
System.out.println(e);
}
return mac;
}
}
class SubscribeCallback implements MqttCallback {
#Override
public void connectionLost (Throwable cause) { }
#Override
public void messageArrived (String topic, MqttMessage message) {
System.out.println("Message arrived. Topic: " + topic
+ " Message: " + message.toString());
if ("I'm gone".equals(topic)) {
System.out.println("Sensor gone!");
}
}
#Override
public void deliveryComplete (IMqttDeliveryToken token) { }
}
I created .class file by executing the following command below
javac -cp org.eclipse.paho.client.mqttv3-1.2.0.jar Subscriber.java
Class file got created without any errors. Next I tried to run the Subscriber class by
java -cp org.eclipse.paho.client.mqttv3-1.2.0.jar Subscriber
I am getting a class not found exception for subscriber
Error: Could not find or load main class Subscriber
Caused by: java.lang.ClassNotFoundException: Subscriber
Note: Both subscriber.java and org.eclipse.paho.client.mqttv3-1.2.0.jar are in same directory
You need to add the current directory to the classpath as well
java -cp .:org.eclipse.paho.client.mqttv3-1.2.0.jar Subscriber
Change the : for ; if running on windows.

How to write simple smack 4.2.3 app that connects to server and answer to user

I have simple smack 3.2.1 application. It connect to xmpp server
and waiting for another user conversation initiation. When user ask question
via chat, application send response (answer). And it is working fine. Here is code:
JabberApplication.java:
package jabberapplication;
import org.jivesoftware.smack.XMPPException;
public class JabberApplication {
public static void main(String[] args) throws XMPPException, InterruptedException {
String username = "USERNAME";
String password = "PASSWORD";
String server = "SERVER";
int port=5222;
XmppManager xmppManager = new XmppManager(server, port);
xmppManager.init();
xmppManager.performLogin(username, password);
xmppManager.setStatus(true, "Hello everyone");
boolean isRunning = true;
while (isRunning) {
Thread.sleep(50);
}
xmppManager.destroy();
}
}
XmppManager.java:
package jabberapplication;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
public class XmppManager {
private final String server;
private final int port;
private XMPPConnection connection;
private ChatManager chatManager;
private MessageListener messageListener;
private ConversationController conversationController;
public XmppManager(String server, int port) {
this.server = server;
this.port = port;
}
public void init() throws XMPPException {
System.out.println(String.format("Initializing connection to server %1$s port %2$d", server, port));
ConnectionConfiguration connectionConfiguration = new ConnectionConfiguration(server, port);
connection = new XMPPConnection(connectionConfiguration);
connection.connect();
System.out.println("Connected: " + connection.isConnected());
chatManager = connection.getChatManager();
chatManager.addChatListener(new MyChatManagerListener());
messageListener = new MyMessageListener();
conversationController = new ConversationController();
}
public void performLogin(String username, String password) throws XMPPException {
if (connection != null && connection.isConnected()) {
connection.login(username, password);
}
}
public void setStatus(boolean available, String status) {
Presence.Type type = available ? Type.available : Type.unavailable;
Presence presence = new Presence(type);
presence.setStatus(status);
connection.sendPacket(presence);
}
public void destroy() {
if (connection != null && connection.isConnected()) {
connection.disconnect();
}
}
public void sendMessage(String message, String buddyJID) throws XMPPException {
System.out.println(String.format("Sending mesage '%1$s' to user %2$s", message, buddyJID));
Chat chat = chatManager.createChat(buddyJID, messageListener);
chat.sendMessage(message);
}
class MyMessageListener implements MessageListener {
#Override
public void processMessage(Chat chat, Message message) {
String from = message.getFrom();
String body = message.getBody();
if (!body.equals("null")) {
System.out.println(String.format("Received message '%1$s' from %2$s", body, from));
try {
chat.sendMessage(conversationController.getAnswer(body));
} catch (XMPPException ex) {
System.out.println(ex.getMessage());
}
}
}
}
class MyChatManagerListener implements ChatManagerListener {
#Override
public void chatCreated(Chat chat, boolean bln) {
int indexAt = chat.getParticipant().indexOf("#");
String username = chat.getParticipant().substring(0, indexAt);
chat.addMessageListener(messageListener);
try {
chat.sendMessage("Hello " + username + " !");
} catch (XMPPException ex) {
System.out.println(ex.getMessage());
}
}
}
}
Well, the question is: How to write similar app using smack library version 4.2.3. It looks like that in 4.2.3 there are no MessageListener and ChatManagerListener classes. Any suggestions ?
Best Regards.
For Smack 4.2.3, ChatManagerListener interface is under org.jivesoftware.smack.chat class (note : chat not Chat).
So, you need to change import to org.jivesoftware.smack.chat.ChatManagerListener.
Also, MessageListener is now change to ChatMessageListener also under org.jivesoftware.smack.chat class.
So, you need to change import to org.jivesoftware.smack.chat.ChatMessageListener.
And rename the implements to as below :
class MyMessageListener implements ChatMessageListener

one broker url with many topics in mqtt

I have two topics and one broker URL. I need to publish to these two topics using one broker URL.
I did it with one broker URL and one topic. Then I tried to do with two topics and write two subscriber class for each topic but when I run two subscriber classes one will shows connection lost.
Suggest some good examples to do this.
MQTTPublisher.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
import org.eclipse.paho.client.mqttv3.MqttDefaultFilePersistence;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
public class MQTTPublisher {
static final String BROKER_URL = "tcp://localhost:1883";// public mosquitto
// server
static final String TOPIC = "iotm/ej";// Change according to your
// application
static final String TOPIC1 = "iotm/stream1";
public static void main(String args[]) {
try {
// Creating new default persistence for mqtt client
MqttClientPersistence persistence = new MqttDefaultFilePersistence(
"/tmp");
// mqtt client with specific url and client id
MqttClient client1 = new MqttClient(BROKER_URL, "Publisher-ID",
persistence);
client.connect();
MqttTopic myTopic = client1.getTopic(TOPIC);
MqttTopic myTopic1 = client1.getTopic(TOPIC1);
String msg = "AMMA!DEVI!dURGA";
System.out.println("Enter the message to publish,Type quit to exit\n");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
msg = br.readLine();
while (!msg.equals("quit")) {
myTopic.publish(new MqttMessage(msg.getBytes()));
System.out.println("Message published on" + TOPIC);
myTopic1.publish(new MqttMessage(msg.getBytes()));
System.out.println("Message published on" + TOPIC1);
msg = br.readLine();
}
myTopic.publish(new MqttMessage(msg.getBytes()));
myTopic1.publish(new MqttMessage(msg.getBytes()));
// client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
MQTTSubscriber.java
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttDefaultFilePersistence;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
public class MQTTSubscriber {
static final String BROKER_URL = "tcp://localhost:1883";// public
// mosquitto server
static final String TOPIC = "iotm/ej"; // Change according to your
public static void main(String args[]) {
try {
// Creating new default persistence for mqtt client
MqttDefaultFilePersistence persistence = new MqttDefaultFilePersistence(
"/tmp");
// mqtt client with specific url and a random client id
MqttClient client1 = new MqttClient(BROKER_URL, "Subscriber-ID",
persistence);
client1.connect();
System.out.println("Subscribing to topic '" + TOPIC + "' from "
+ client1.getServerURI());
// Subscribing to specific topic
client1.subscribe(TOPIC);
// It will trigger when a new message is arrived
MqttCallback callback = new MqttCallback() {
#Override
public void messageArrived(MqttTopic arg0, MqttMessage arg1)
throws Exception {
System.out.println("Message:"
+ new String(arg1.getPayload()));
}
#Override
public void deliveryComplete(MqttDeliveryToken arg0) {
}
#Override
public void connectionLost(Throwable arg0) {
System.out.println("Connection lost");
}
};
// Continue waiting for messages until the Enter is pressed
client1.setCallback(callback);
/*
* System.out.println("Press <Enter> to exit"); try {
* System.in.read(); } catch (IOException e) { // If we can't read
* we'll just exit }
*/
// client.disconnect();
// System.out.println("Client Disconnected");
} catch (MqttException e) {
e.printStackTrace();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
MQTTSubscriber2.java
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttDefaultFilePersistence;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
public class MQTTSubscriber2 {
static final String BROKER_URL = "tcp://localhost:1883";// public
// mosquitto server
static final String TOPIC = "iotm/stream1";
public static void main(String args[]) {
try {
// Creating new default persistence for mqtt client
MqttDefaultFilePersistence persistence = new MqttDefaultFilePersistence(
"/tmp");
// mqtt client with specific url and a random client id
MqttClient client = new MqttClient(BROKER_URL, "Subscriber-ID",
persistence);
client.connect();
System.out.println("Subscribing to topic '" + TOPIC + "' from "
+ client.getServerURI());
// Subscribing to specific topic
client.subscribe(TOPIC);
// It will trigger when a new message is arrived
MqttCallback callback = new MqttCallback() {
#Override
public void messageArrived(MqttTopic arg0, MqttMessage arg1)
throws Exception {
System.out.println("Message:"
+ new String(arg1.getPayload()));
}
#Override
public void deliveryComplete(MqttDeliveryToken arg0) {
}
#Override
public void connectionLost(Throwable arg0) {
System.out.println("Connection lost");
}
};
// Continue waiting for messages until the Enter is pressed
client.setCallback(callback);
/*
* System.out.println("Press <Enter> to exit"); try {
* System.in.read(); } catch (IOException e) { // If we can't read
* we'll just exit }
*/
// client.disconnect();
// System.out.println("Client Disconnected");
} catch (MqttException e) {
e.printStackTrace();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
If you are running 2 separate instances of the subscriber code then they will both need different client ids. If you run 2 with the same then the first will be disconnected from the broker when the second connects.

Categories