Push messages from server

The familiar HTTP request/response model was designed to be easy to work with and scalable. However, nowadays end users demand a lot more from the web than it was originally designed for. The HTTP protocol requires users to initiate the request in order to receive a response. But developers need a way to send data from server to clients without them asking for it; in other words, they need to "push" data to clients, like pushing the latest bidding price of a product on an auction site or fast-moving stock prices in a financial application.

GIF of application server pushing data to connected client.

This quickstart guide demonstrates how to

  • subscribe to messages from an application server
  • push data from an application server to all connected clients

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

Create a subscriber client

To subscribe to messages pushed from your application server, a client, be it a browser, a mobile app or an IoT device, needs to connect to your Web PubSub resource first, and listens for appropriate message event.

Create a project directory named subscriber and install required dependencies

mkdir subscriber
cd subscriber
npm init -y
    
# The client SDK is available as a module on NPM
npm install @azure/web-pubsub-client

Connect to your Web PubSub resource and register a listener for the server-message event

A client uses a Client Access URL to connect and authenticate with your resource. This URL follows a pattern of wss://<service_name>.webpubsub.azure.com/client/hubs/<hub_name>?access_token=<token>. A client can have a few ways to obtain the Client Access URL. For this quick start, you can copy and paste one from Azure portal shown in the following diagram. 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.

The diagram shows how to get client access url.

As shown in the diagram above, the client joins the hub named myHub1.

In the subscriber project folder, create a file named subscribe.js with the following code

const { WebPubSubClient } = require("@azure/web-pubsub-client");

// Instantiates the client object
// <client-access-url> is copied from Azure portal mentioned above
const client = new WebPubSubClient("<client-access-url>")

// Registers a handler for the "server-message" event
client.on("server-message", (e) => {
    console.log(`Received message ${e.message.data}`)
});

// Before a client can receive a message, 
// you must invoke start() on the client object.
client.start();

Run the program

node subscribe.js

Now this client establishes a connection with your Web PubSub resource and is ready to receive messages pushed from your application server.

Push messages from your application server

Now that you have a client connected your Web PubSub resource, you can push messages from an application server at any time using the server SDK provided by Web PubSub.

Create a new project directory named publisher and install required dependencies

mkdir publisher
cd publisher

npm init

# This command installs the server SDK from NPM, 
# which is different from the client SDK you used in subscribe.js
npm install --save @azure/web-pubsub

Create a publish.js file with the following code

const { WebPubSubServiceClient } = require('@azure/web-pubsub');

// This is the hub name we used on Azure portal when generating the Client Access URL. 
// It ensures this server can push messages to clients in the hub named "myHub1".
const hub = "myHub1";
    
let server = new WebPubSubServiceClient(process.env.WebPubSubConnectionString, hub);

// By default, the content type is `application/json`. 
// Specify contentType as `text/plain` for this demo.
server.sendToAll(process.argv[2], { contentType: "text/plain" });

The server.sendToAll() call sends a message to all connected clients in a hub.

Get the connection string

Important

A connection string includes authorization information required for your application to access Web PubSub service. The access key inside the connection string is similar to a root password for your service.

For this quickstart guide, we'll get it from Azure portal as shown below. A diagram shows how to get client access url.

Run the server program

Run the following commands in a new command shell.

# Set the environment variable for your connection string.
export WebPubSubConnectionString="<Put your connection string here>" 

node publish.js "Hello World"

Observe the received messages on the client side

GIF of demonstrating an app server pushing data to connected client.

Try running the same "subscribe" program in multiple command shells to stimulate more than clients. As soon as the "publish" program is run, you should see messages being delivered in real-time to all these clients.

Summary

This quickstart demonstrates how easy it's to push messages from an application server to all connected clients in a hub. Additionally, Web PubSub allows you to push messages to

  • a subset of the clients in a hub
  • a particular group in a hub
  • a subset of clients in a group

These APIs enable a wealth of use cases, allowing developers to focus on unique business logic while be assured that Web PubSub offers low latency (<100ms), high availability and massive scale (million+ simultaneous connections).

Next steps

In the next step, we'll explore how to work with the event system of Web PubSub, necessary to build complete web applications.