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.
Related
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
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.
This is my first time messing around with Sockets, and it was working up until now. Basically, I have a custom ServerSocket class named Server and a custom Socket class named Client.
When Client tries to connect to Server, Server performs a little check to make sure it is actually Client that it trying to make the connection, and not some other socket, because Client has certain methods that I need.
However, this check always returns false. Here is my Server connection code:
package me.eli.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import me.eli.client.Client;
public class Server extends ServerSocket {
private final Map<Client, IOPair> clients = new HashMap<Client, IOPair>();
public Server(final int port) throws IOException {
super(port);
System.out.println("Server started on " + getLocalPort() + "... Waiting for client!");
}
public Client waitOnClient() throws IOException {
final Socket generalClient = accept();
final Client client;
if(!(generalClient instanceof Client)) {
client = null;
PrintWriter out = new PrintWriter(generalClient.getOutputStream(), true);
out.println("Access denied: " + generalClient.getClass().getSimpleName());
log("Invalid client: " + generalClient.getClass().getName() + " (" + generalClient.getInetAddress().getHostAddress() + ")");
out.close();
} else
client = (Client) generalClient;
if(client == null)
return null;
client.setServer(this);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
broadcast(client.getName() + " has joined.");
clients.put(client, new IOPair(in, out));
System.out.println("Client (" + client.getName() + ") connected from " + client.getInetAddress().getHostAddress());
out.println("Connected! Welcome to the server.");
return client;
}
#Override
public void close() throws IOException {
for(Client c : getClients())
kick(c, "Server closed");
super.close();
}
public void kick(Client c, String reason) {
try {
c.message("disconnect", reason);
c.close();
} catch(IOException e) {
log("Failed to kick " + c.getName() + ": " + e.getMessage());
c.message("error", "Failed to disconnect");
}
}
public void log(String message) {
getServerOut().println(message);
}
public void log(String source, String message) {
log("<" + source + "> " + message);
}
public void broadcast(String message) {
log("broadcast", message);
for(Client c : getClients())
c.message("broadcast", message);
}
public Client[] getClients() {
return clients.keySet().toArray(new Client[clients.keySet().size()]);
}
public BufferedReader getClientIn(Client c) {
return clients.get(c).getIn();
}
public PrintWriter getClientOut(Client c) {
return clients.get(c).getOut();
}
public InputStream getServerIn() {
return System.in;
}
public PrintStream getServerOut() {
return System.out;
}
public static boolean isServerRunningOn(final int port) {
try {
new ServerSocket(port).close();
return false;
} catch(IOException e) {
return true;
}
}
}
And here is my Client connection code:
package me.eli.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import me.eli.server.IOPair;
import me.eli.server.Server;
public class Client extends Socket {
private Server server;
private final IOPair serverio;
private final String name;
public Client(final String host, final int port) throws IOException {
this(host, port, "Guest-" + (int) (Math.random() * 10000));
}
public Client(final String host, final int port, final String name) throws IOException {
super(host, port);
System.out.println("Connected to server on " + host + ":" + port);
BufferedReader in = new BufferedReader(new InputStreamReader(getInputStream()));
PrintWriter out = new PrintWriter(getOutputStream(), true);
this.name = name;
this.serverio = new IOPair(in, out);
String input;
if((input = in.readLine()) != null)
System.out.println("<Welcome message> " + input);
out.println("Yay! I'm connected!");
}
#Override
public synchronized void close() throws IOException {
if(serverio != null) {
if(server != null)
server.broadcast(getName() + " has disconnected.");
message("server", "Disconnected.");
super.close();
serverio.getIn().close();
serverio.getOut().close();
} else
super.close();
}
public void message(String source, String message) {
getClientOut().println("<" + source + "> " + message);
}
public String getName() {
return name;
}
public void setServer(Server server) {
this.server = server;
}
public Server getServer() {
return server;
}
public BufferedReader getServerIn() {
return serverio.getIn();
}
public PrintWriter getServerOut() {
return serverio.getOut();
}
public InputStream getClientIn() {
return System.in;
}
public PrintStream getClientOut() {
return System.out;
}
}
I'm not the most experienced with networking, but this confuses me because I do indeed connect with my Client class. Thanks in advance!
Server performs a little check to make sure it is actually Client that it trying to make the connection
Impossible and nonsensical. The Client class is at the other end of the connection. It is not magically transmitted to your accept() method. If you want to validate your client you will have to build something into your application protocol.
Notes:
Calling Client.setServer() is similarly futile. It is not magically transmitted to the client.
It is possible to get your ServerSocket-derived class to create Client objects instead of Socket objects in its accept() method, but that doesn't actually solve the issue you're trying to solve.
I am trying to implement Orchid Tor lib with Java code; unfortunately and because the lack of documentation I am not able to make it work, this is what I did:
....................
private final static String DEFAULT_SOCKS_PORT = "9050";
TorClient torClient = new TorClient();
torClient.addInitializationListener(new TorInitializationListener() {
#Override
public void initializationProgress(String string, int i) {
System.out.println(">>> [ "+ i + "% ]: "+ string);
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void initializationCompleted() {
try {
System.out.println("Tor is ready to go!");
setSystemProperties("127.0.0.1","8118");
System.out.println("is online "+isOnline()); //isOnilne is just function return true if connected by pinging google.com
} catch (Exception e) {
e.printStackTrace();
}
}
});
torClient.enableDashboard(8118);
torClient.enableSocksListener(9050);
torClient.start();
private static void setSystemProperties(String host, String port)
{
System.setProperty("proxyHost", host);
System.setProperty("proxyPort", port);
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", port);
System.setProperty("https.proxyHost", host);
System.setProperty("https.proxyPort", port);
System.setProperty("socks.proxyHost", host);
System.setProperty("socks.proxyPort", DEFAULT_SOCKS_PORT);
System.setProperty("socksProxyHost", host);
System.setProperty("socksProxyPort", DEFAULT_SOCKS_PORT);
}
This seems to work using Java8.
Dependencies: orchid-1.0.0.jar, jsoup-1.8.2.jar & commons-io-2.4.jar
package orchiddemo;
import com.subgraph.orchid.TorClient;
import com.subgraph.orchid.TorInitializationListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class OrchidDemo {
private static TorClient client;
public static void main(String[] args) {
startOrchid();
}
private static void startOrchid() {
//listen on 127.0.0.1:9150 (default)
client = new TorClient();
client.addInitializationListener(createInitalizationListner());
client.start();
client.enableSocksListener();//or client.enableSocksListener(yourPortNum);
}
private static void stopOrchid() {
client.stop();
}
public static TorInitializationListener createInitalizationListner() {
return new TorInitializationListener() {
#Override
public void initializationProgress(String message, int percent) {
System.out.println(">>> [ " + percent + "% ]: " + message);
}
#Override
public void initializationCompleted() {
System.out.println("Tor is ready to go!");
doTests();
}
};
}
private static void doTests() {
testOrchidUsingProxyObject();
testOrchidUsingSystemPropsProxy();
testOrchidUsingSocket();
}
private static void testOrchidUsingProxyObject() {
Thread thread = new Thread() {
#Override
public void run() {
try {
//Caution: Native Java DNS lookup will occur outside of the tor network.
//Monitor traffic on port 53 using tcpdump or equivalent.
URL url = new URL("https://wtfismyip.com/");
Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("localhost", 9150));
HttpURLConnection uc = (HttpURLConnection) url.openConnection(proxy);
uc.setConnectTimeout(10000);
Document document = Jsoup.parse(IOUtils.toString(uc.getInputStream()));
String result = document.select("div[id=tor").text();
System.out.println("testOrchidUsingProxyObject: " + result);
} catch (Exception ex) {
Logger.getLogger(OrchidDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
thread.start();
}
private static void testOrchidUsingSystemPropsProxy() {
Thread thread = new Thread() {
#Override
public void run() {
try {
//Caution: Native Java DNS lookup will occur outside of the tor network.
//Monitor traffic on port 53 using tcpdump or equivalent.
System.setProperty("socksProxyHost", "127.0.0.1");
System.setProperty("socksProxyPort", "9150");
Document document = Jsoup.connect("https://wtfismyip.com/").get();
String result = document.select("div[id=tor").text();
System.out.println("testOrchidUsingSystemPropsProxy: " + result);
System.setProperty("socksProxyHost", "");
System.setProperty("socksProxyPort", "");
} catch (Exception ex) {
Logger.getLogger(OrchidDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
thread.start();
}
private static void testOrchidUsingSocket() {
Thread thread = new Thread() {
#Override
public void run() {
try {
// This does not appear to leak the DNS lookup, but requires confirmation!
Socket socket = client.getSocketFactory().createSocket("www.google.com", 80);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer.println("GET /");
String line;
System.out.println("testOrchidUsingSocket: ");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
socket.close();
} catch (Exception ex) {
Logger.getLogger(OrchidDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
thread.start();
}
}
The DNS leak is a drama, but silvertunnel can help: NetAddressNameService
I'm hoping someone might know of a better way....
Cheers
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.