Send a message to an MQTT client

IBM MQ applications can send MQTT v3 clients messages by publishing to subscriptions created by clients, or by sending messages directly. MQTT clients can send messages to one another by publishing to topics subscribed to by other clients.


An MQTT client subscribes to a publication, which it receives from IBM MQ

Do the task, Publishing a message to the MQTT client utility from IBM MQ Explorer to send a publication from IBM MQ to an MQTT client.

The standard way for an MQTT v3 client to receive messages is for it to create a subscription to a topic, or set of topics. In the example code snippet, Figure 1, the MQTT client subscribes using the topic string MQTT Examples. An IBM MQ C application, Figure 2, publishes to the topic using the topic string MQTT Examples. In the code snippet Figure 3, the MQTT client receives the publication in the callback method, messageArrived.

For further information about how to configure IBM MQ to send publications in response to subscriptions from MQTT clients, see Publishing a message in response to an MQTT client subscription.


An IBM MQ application sends a message directly to an MQTT client

Do the task, Send a message to an MQTT client using IBM MQ Explorer to send a message directly from IBM MQ to an MQTT client.

A message sent in this way to an MQTT client is called an unsolicited message. MQTT v3 clients receive unsolicited messages as publications with a topic name set. The telemetry (MQXR) service sets the topic name to the remote queue name.

For further information about how to configure IBM MQ to send messages directly to MQTT clients, see Send a message to a client directly.


An MQTT client publishes a message

An MQTT v3 client can publish a message that is received by another MQTT v3 client, but it cannot send an unsolicited message. The code snippet Figure 4 shows how an MQTT v3 client, written in Java, publishes a message.

The typical pattern for sending a message to one specific MQTT v3 client, is for each client to create a subscription to its own ClientIdentifier. Do the task Publishing a message to a specific MQTT v3 client to publish a message from one MQTT client to another MQTT client using ClientIdentifier as a topic string.


Example code snippets

The code snippet in Figure 1 shows how an MQTT client written in Java creates a subscription. It also needs a callback method, messageArrived to receive publications for the subscription.

Figure 1. MQTT v3 client subscriber
String    clientId = String.format("%-23.23s", 
                     System.getProperty("user.name") + "_" + 
                     (UUID.randomUUID().toString())).trim()).replace('-', '_');
MqttClient  client = new MqttClient("localhost", clientId);
String topicString = "MQTT Examples";
int            QoS = 1;
client.subscribe(topicString, QoS);

The code snippet in Figure 2 shows how an IBM MQ application written in C sends a publication. The code snippet is extracted from the task, Create a publisher to a variable topic

Figure 2. IBM MQ publisher
/* Define and set variables to.defaults */
/* Omitted lines declaring variables    */
char * topicName   = ""
char * topicString = "MQTT Examples"
char * publication = "Hello world!";
do {
  MQCONN(qMgrName, &Hconn, &CompCode, &Reason);
  if (CompCode != MQCC_OK) break;
  td.ObjectType = MQOT_TOPIC;    /* Object is a topic             */
  td.Version = MQOD_VERSION_4;   /* Descriptor needs to be V4     */
  strncpy(td.ObjectName, topicName,  MQ_TOPIC_NAME_LENGTH);
  td.ObjectString.VSPtr = topicString;
  td.ObjectString.VSLength = (MQLONG)strlen(topicString);
  MQOPEN(Hconn, &td, MQOO_OUTPUT | MQOO_FAIL_IF_QUIESCING, &Hobj, &CompCode, &Reason);
  if (CompCode != MQCC_OK) break;
  pmo.Options = MQPMO_FAIL_IF_QUIESCING | MQPMO_RETAIN;
  MQPUT(Hconn, Hobj, &md, &pmo, (MQLONG)strlen(publication)+1, publication, &CompCode, &Reason);
  if (CompCode != MQCC_OK) break;
  MQCLOSE(Hconn, &Hobj, MQCO_NONE, &CompCode, &Reason);
  if (CompCode != MQCC_OK) break;
  MQDISC(&Hconn, &CompCode, &Reason);
} while (0);

When the publication arrives, the MQTT client calls the messageArrived method of the MQTT application client MqttCallback class.

Figure 3. messageArrived method
public class CallBack implements MqttCallback {
  public void messageArrived(MqttTopic topic, MqttMessage message) {
    try {
      System.out.println("Message arrived: \"" + message.toString()
          + "\" on topic \"" + topic.toString() + "\"");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
// ... Other callback methods 
}

Figure 4 shows an MQTT v3 publishing a message to the subscription created in Figure 1.

Figure 4. MQTT v3 client publisher
      String          address = "localhost";
      String         clientId = String.format("%-23.23s", 
                                System.getProperty("user.name") + "_" + 
                                (UUID.randomUUID().toString())).trim()).replace('-', '_');
      MqttClient       client = new MqttClient(address, clientId);
      String      topicString = "MQTT Examples";
      MqttTopic         topic = client.getTopic(Example.topicString);
      String     publication  = "Hello world";
      MqttMessage     message = new MqttMessage(publication.getBytes());
      MqttDeliveryToken token = topic.publish(message);

Parent topic: MQ Telemetry overview