0

I am trying to develop a publish/subscribe application where a Java program is a publisher and nodejs program is a subscriber. The Java client connects to MQTT server and sends some random data. The NodeJS client should subscribe to the topic the java client has registered. I am getting the data from java client on to the NodeJS console, but I have to print that data asynchronously on a web page.

Here's the code I've written.

MqttPublishSample.java

public class MqttPublishSample {

    public static void main(String[] args) {

        String topic = "MQTT-Examples";
        String content = "HelloWorld";
        int qos = 2;
        int i =0;
        String broker = "tcp://localhost:1883";
        String clientId = "JavaSample";
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            System.out.println("Connecting to broker: " + broker);
            sampleClient.connect(connOpts);
            System.out.println("Connected");
            while(i < 100) 
            {                           
                int num = (int) (Math.random() * 2); 
                String text = content + num;
                System.out.println("Publishing message: "+content+ " "+ num); 
                MqttMessage message = new MqttMessage(text.getBytes());
                message.setQos(qos);
                sampleClient.publish(topic, message);
                System.out.println("Message published");
                i++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            // System.out.println("Publishing message: " + content);

            /*sampleClient.disconnect();
            System.out.println("Disconnected");
            System.exit(0);*/
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
}

app.js

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  client.on('connect', function() {
        console.log("Connection Successful");
        client.subscribe('MQTT-Examples');

    });
    var content;
    client.on('message', function (topic, message) {
    content = message;
      console.log(message.toString());
    });
res.render('index', { title: content });
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

I tried printing the message on the web page but I am unable to see any message. I need to asynchronously print the data on the web page. Any help with how to proceed. Thanks!

1 Answer 1

2

try moving the line res.render('index', { title: content }); inside the callback for client.on e.g:

var express = require('express');
var app = express();

/*
 * MQTT Client
 */
var content = ""; //buffer

client.on('connect', function() {
  console.log("Connection Successful");
  client.subscribe('MQTT-Examples');
});

client.on('message', function(topic, message) {
  content += message.toString() + "<br>";
  console.log(message.toString());

});

/*
 * Express
 */
app.get('/', function(req, res) {
  res.render('index', {
    title: content
  });
});

app.listen(3000, function() {
  console.log('Example app listening on port 3000!');
});

Update

I did update to code, in the new code you will be able to see all messages received every time you reload the web page.

In the previous implementation was a kind of long polling, the resource will wait for a message from the broker.

Hope it helps.

Sign up to request clarification or add additional context in comments.

1 Comment

This time the page reloads forever. It doesn't even print the connection successful message on the console. Not sure if it's running the client method or not?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.