Publish/subscribe among MQTT clients

GIF of pub/sub among clients without an application server.

This quickstart guide demonstrates how to

  • connect to your Web PubSub resource
  • subscribe to messages on a specific topic
  • publish messages to a topic

Prerequisites

  • A Web PubSub resource. If you haven't created one, you can follow the guidance: Create a Web PubSub resource
  • A code editor, such as Visual Studio Code
  • Install the dependencies for the language you plan to use

Note

Except for the MQTT client libraries mentioned belows, you can choose any standard MQTT client libraries that meet the following requirements to connect to Web PubSub:

  • Support WebSocket transport.
  • Support MQTT protocol 3.1.1 or 5.0.
mkdir pubsub_among_clients
cd pubsub_among_clients

npm install mqtt

Connect to Web PubSub

An MQTT uses a Client Access URL to connect and authenticate with your resource. This URL follows a pattern of wss://<service_name>.webpubsub.azure.com/clients/mqtt/hubs/<hub_name>?access_token=<token>.

A client can have a few ways to obtain the Client Access URL. It's best practice to not hard code the Client Access URL in your code. In the production world, we usually set up an app server to return this URL on demand. Generate Client Access URL describes the practice in detail.

For this quick start, you can copy and paste one from Azure portal shown in the following diagram.

The diagram shows how to get MQTT client access url.

As shown in the preceding code, the client has the permissions to send messages to topic group1 and to subscribe to topic group2.

There are some limitations you should follow in your MQTT clients, otherwise the connection will be rejected. These MQTT protocol parameters include:

  • Protocol versions: 3.1.1 or 5.0.
  • Client ID format
    • Allowed characters: 0-9, a-z, A-Z
    • Length is between 1 and 128
  • Keep-alive interval for MQTT 3.1.1: 1 - 180 seconds
  • Last-will Topic format: Not empty, and contains at least one nonwhitespace character. The max length is 1024.
  • Last-will message size: up to 2,000 bytes

The following code shows how to connect MQTT clients to WebPubSub with MQTT protocol version 5.0, clean start, 30-seconds session expiry interval.

Create a file with name index.js and add following code

const mqtt = require('mqtt');
var client = mqtt.connect(`wss://<service_name>.webpubsub.azure.com/clients/mqtt/hubs/<hub_name>?access_token=<token>`,
        {
            clientId: "client1",
            protocolVersion: 5, // Use MQTT 5.0 protocol
            clean: true,
            properties: {
                sessionExpiryInterval: 30,
            },
        });

Troubleshooting

If your client failed to connect, you could use the Azure Monitor for troubleshooting. See Monitor Azure Web PubSub for more details.

You can check the connection parameters and get more detailed error messages from the Azure Monitor. For example, the following screenshot of Azure Log Analytics shows that the connection was rejected because it set an invalid keep alive interval. Screenshot of Azure Log Analytics.

Subscribe to a topic

To receive messages from topics, the client

  • must subscribe to the topic it wishes to receive messages from
  • has a callback to handle message event

The following code shows a client subscribes to topics named group2.

// ...code from the last step

// Provide callback to the message event.
client.on("message", async (topic, payload, packet) => {
    console.log(topic, payload)
});

// Subscribe to a topic.
client.subscribe("group2", { qos: 1 }, (err, granted) => { console.log("subscribe", granted); })

Publish a message to a group

In the previous step, we've set up everything needed to receive messages from group1, now we send messages to that group.

// ...code from the last step

// Send message "Hello World" in the "text" format to "group1".
client.publish("group1", "Hello World!")

Next steps

By using the client SDK, you now know how to

  • connect to your Web PubSub resource
  • subscribe to topics
  • publish messages to topics

Next, you learn how to push messages in real-time from an application server to your clients.