Tutorial: Publish and subscribe messages using WebSocket API and Azure Web PubSub service SDK
บทความ
The Azure Web PubSub service helps you easily build real-time web messaging applications. In this tutorial, you learn how to subscribe to the service using the WebSocket API and publish messages using the Web PubSub service SDK.
In this tutorial, you learn how to:
Create a Web PubSub service instance
Generate the full URL to establish the WebSocket connection
Create a Web PubSub subscriber client to receive messages using the standard WebSocket protocol
Create a Web PubSub publisher client to publish messages using the Web PubSub service SDK
Follow these steps to set up Azure CLI and your project environment.
Open a command shell.
Upgrade to the latest version of the Azure CLI.
az upgrade
Install the Azure CLI extension for Web PubSub.
az extension add --name webpubsub
Sign in to Azure CLI. Following the prompts, enter your Azure credentials.
az login
Create a resource group
A resource group is a logical container into which Azure resources are deployed and managed. Use the az group create command to create a resource group named myResourceGroup in the eastus location.
az group create --name myResourceGroup --location EastUS
1. Create an Azure Web PubSub instance
Create a Web PubSub instance
To create a Web PubSub instance in the resource group you created, use the Azure CLI az webpubsub create command. The following command creates a Free Web PubSub resource under resource group myResourceGroup in EastUS:
Each Web PubSub resource must have a unique name. Replace <your-unique-resource-name> with the name of your Web PubSub instance in the following command.
The output of this command shows properties of the newly created resource. Take note of the following roperties:
name: The Web PubSub name you provided in the --name parameter above.
hostName: In the example, the host name is <your-unique-resource-name>.webpubsub.azure.com/.
At this point, your Azure account is the only one authorized to perform any operations on this new resource.
Get the connection string
Important
A connection string includes the authorization information required for your application to access Azure Web PubSub service. The access key inside the connection string is similar to a root password for your service. In production environments, always be careful to protect your access keys. Use Azure Key Vault to manage and rotate your keys securely. Avoid distributing access keys to other users, hard-coding them, or saving them anywhere in plain text that is accessible to others. Rotate your keys if you believe they may have been compromised.
Use the Azure CLI az webpubsub key command to get the ConnectionString of the service. Replace the <your-unique-resource-name> placeholder with the name of your Azure Web PubSub instance.
az webpubsub key show --resource-group myResourceGroup --name <your-unique-resource-name> --query primaryConnectionString --output tsv
Copy the connection string to use later.
Create a subscriber client
Clients connect to the Azure Web PubSub service through the standard WebSocket protocol using JSON Web Token (JWT) authentication. The service SDK provides helper methods to generate the token. In this tutorial, the subscriber directly generates the token from ConnectionString. In real applications, a server-side application usually handles the authentication/authorization workflow. To better understand the workflow, see the tutorial Build a chat app.
First, create a project directory named subscriber for this project and install required dependencies:
The package Websocket.Client is a third-party package supporting WebSocket connections. You can use any API/library that supports WebSocket.
The SDK package Azure.Messaging.WebPubSub helps to generate the JWT token.
mkdir subscriber
cd subscriber
dotnet new console
dotnet add package Websocket.Client --version 4.3.30
dotnet add package Azure.Messaging.WebPubSub --version 1.0.0
Replace the code in the Program.cs with the following code that connects to the service:
using System;
using System.Threading.Tasks;
using Azure.Messaging.WebPubSub;
using Websocket.Client;
namespace subscriber
{
class Program
{
static async Task Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: subscriber <connectionString> <hub>");
return;
}
var connectionString = args[0];
var hub = args[1];
// Either generate the URL or fetch it from server or fetch a temp one from the portal
var serviceClient = new WebPubSubServiceClient(connectionString, hub);
var url = serviceClient.GetClientAccessUri();
using (var client = new WebsocketClient(url))
{
// Disable the auto disconnect and reconnect because the sample would like the client to stay online even no data comes in
client.ReconnectTimeout = null;
client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
await client.Start();
Console.WriteLine("Connected.");
Console.Read();
}
}
}
}
The code creates a WebSocket connection that is connected to a hub in Web PubSub. A hub is a logical unit in Web PubSub where you can publish messages to a group of clients. Key concepts contains the detailed explanation about the terms used in Web PubSub.
The Web PubSub service uses JSON Web Token (JWT) authentication. The sample code uses WebPubSubServiceClient.GetClientAccessUri() in Web PubSub SDK to generate a URL to the service that contains the full URL with a valid access token.
After the connection is established, your client receives messages through the WebSocket connection. The client uses client.MessageReceived.Subscribe(msg => ...)); to listen for incoming messages.
To start the subscriber, run the following command replacing <Web-PubSub-connection-string> with the connection string you copied earlier:
dotnet run <Web-PubSub-connection-string> "myHub1"
First, create a project directory named subscriber and install required dependencies:
Use the WebSocket API to connect to the Web PubSub service. Create a subscribe.js file with the following code:
const WebSocket = require('ws');
const { WebPubSubServiceClient } = require('@azure/web-pubsub');
async function main() {
const hub = "pubsub";
let service = new WebPubSubServiceClient(process.env.WebPubSubConnectionString, hub);
let token = await service.getClientAccessToken();
let ws = new WebSocket(token.url);
ws.on('open', () => console.log('connected'));
ws.on('message', data => console.log('Message received: %s', data));
}
main();
The code creates a WebSocket connection that is connected to a hub in Web PubSub. A hub is a logical unit in Web PubSub where you can publish messages to a group of clients. Key concepts contains the detailed explanation about the terms used in Web PubSub.
The Web PubSub service uses JSON Web Token (JWT) authentication. The sample code uses WebPubSubServiceClient.GetClientAccessUri() in Web PubSub SDK to generate a URL to the service that contains the full URL with a valid access token.
After the connection is established, your client receives messages through the WebSocket connection. The client uses client.MessageReceived.Subscribe(msg => ...)); to listen for incoming messages.
Run the following command replacing <Web-PubSub-connection-string> with the connection string you copied earlier. If you're using Windows command shell, you can use set instead of export.
Use the WebSocket API to connect to the Web PubSub service. Create a subscribe.py file with the following code:
import asyncio
import sys
import websockets
from azure.messaging.webpubsubservice import WebPubSubServiceClient
async def connect(url):
async with websockets.connect(url) as ws:
print('connected')
while True:
print('Received message: ' + await ws.recv())
if __name__ == '__main__':
if len(sys.argv) != 3:
print('Usage: python subscribe.py <connection-string> <hub-name>')
exit(1)
connection_string = sys.argv[1]
hub_name = sys.argv[2]
service = WebPubSubServiceClient.from_connection_string(connection_string, hub=hub_name)
token = service.get_client_access_token()
try:
asyncio.get_event_loop().run_until_complete(connect(token['url']))
except KeyboardInterrupt:
pass
The code creates a WebSocket connection that is connected to a hub in Web PubSub. A hub is a logical unit in Web PubSub where you can publish messages to a group of clients. Key concepts contains the detailed explanation about the terms used in Web PubSub.
The Web PubSub service uses JSON Web Token (JWT) authentication. The sample code uses WebPubSubServiceClient.GetClientAccessUri() in Web PubSub SDK to generate a URL to the service that contains the full URL with a valid access token.
After the connection is established, your client will receive messages through the WebSocket connection. Use await ws.recv() to listen for incoming messages.
Run the following command replacing <Web-PubSub-connection-string> with the connection string you copied earlier:
First, create a project directory named pubsub for this tutorial.
mkdir pubsub
cd pubsub
Inside the pubsub directory, use Maven to create a new console app called webpubsub-quickstart-subscriber, then go to the webpubsub-quickstart-subscriber directory:
In Web PubSub, you can connect to the service and subscribe to messages through WebSocket connections. WebSocket is a full-duplex communication channel allowing the service to push messages to your client in real time. You can use any API or library that supports WebSocket. For this sample, we use package Java-WebSocket.
Go to the /src/main/java/com/webpubsub/quickstart directory.
Edit replace the contents of the App.java file with the following code:
package com.webpubsub.quickstart;
import com.azure.messaging.webpubsub.*;
import com.azure.messaging.webpubsub.models.*;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Connect to Azure Web PubSub service using WebSocket protocol
*/
public class App
{
public static void main( String[] args ) throws IOException, URISyntaxException
{
if (args.length != 2) {
System.out.println("Expecting 2 arguments: <connection-string> <hub-name>");
return;
}
WebPubSubServiceClient service = new WebPubSubServiceClientBuilder()
.connectionString(args[0])
.hub(args[1])
.buildClient();
WebPubSubClientAccessToken token = service.getClientAccessToken(new GetClientAccessTokenOptions());
WebSocketClient webSocketClient = new WebSocketClient(new URI(token.getUrl())) {
@Override
public void onMessage(String message) {
System.out.println(String.format("Message received: %s", message));
}
@Override
public void onClose(int arg0, String arg1, boolean arg2) {
// TODO Auto-generated method stub
}
@Override
public void onError(Exception arg0) {
// TODO Auto-generated method stub
}
@Override
public void onOpen(ServerHandshake arg0) {
// TODO Auto-generated method stub
}
};
webSocketClient.connect();
System.in.read();
}
}
This code creates a WebSocket connection that is connected to a hub in Azure Web PubSub. A hub is a logical unit in Azure Web PubSub where you can publish messages to a group of clients. Key concepts contains the detailed explanation about the terms used in Azure Web PubSub.
The Web PubSub service uses JSON Web Token (JWT) authentication. The sample code uses WebPubSubServiceClient.GetClientAccessUri() in Web PubSub SDK to generate a URL to the service that contains the full URL with a valid access token.
After connection is established, your client will receive messages through the WebSocket connection. Use onMessage(String message) to listen for incoming messages.
To start the subscriber app, go to the webpubsub-quickstart-subscriber directory and run the following command. Replace <Web-PubSub-connection-string> with the connection string you copied earlier.
Create a publisher using the Azure Web PubSub SDK to publish a message to the connected client. For this project, you need to open another command shell.
First, create a project directory named publisher and install required dependencies:
mkdir publisher
cd publisher
dotnet new console
dotnet add package Azure.Messaging.WebPubSub
Update the Program.cs file to use the WebPubSubServiceClient class and send messages to the clients.
using System;
using System.Threading.Tasks;
using Azure.Messaging.WebPubSub;
namespace publisher
{
class Program
{
static async Task Main(string[] args)
{
if (args.Length != 3) {
Console.WriteLine("Usage: publisher <connectionString> <hub> <message>");
return;
}
var connectionString = args[0];
var hub = args[1];
var message = args[2];
// Either generate the token or fetch it from server or fetch a temp one from the portal
var serviceClient = new WebPubSubServiceClient(connectionString, hub);
await serviceClient.SendToAllAsync(message);
}
}
}
The SendToAllAsync() call simply sends a message to all connected clients in the hub.
Send a message by running the following command. Replace <Web-PubSub-connection-string> with the connection string you copied earlier.
dotnet run <Web-PubSub-connection-string> "myHub1" "Hello World"
Verify that the subscriber's command shell receives the message:
Message received: Hello World
First, create a project directory named publisher and install required dependencies:
Use Azure Web PubSub SDK to publish a message to the service. Create a publish.js file with the following code:
const { WebPubSubServiceClient } = require('@azure/web-pubsub');
const hub = "pubsub";
let service = new WebPubSubServiceClient(process.env.WebPubSubConnectionString, hub);
// by default it uses `application/json`, specify contentType as `text/plain` if you want plain-text
service.sendToAll(process.argv[2], { contentType: "text/plain" });
The service.sendToAll() call simply sends a message to all connected clients in a hub.
To send a message, run the following command replacing <Web-PubSub-connection-string> with the connection string you copied earlier. If you're using the Windows command shell, you can use set instead of export.
Check the previous command shell to that the subscriber received the message:
Received message: Hello World
Go to the pubsub directory. Use Maven to create a publisher console app webpubsub-quickstart-publisher and go to the webpubsub-quickstart-publisher directory:
Use the Azure Web PubSub SDK to publish a message to the service. Go to the /src/main/java/com/webpubsub/quickstart directory, open the App.java file in your editor, and replace the contents with the following code:
package com.webpubsub.quickstart;
import com.azure.messaging.webpubsub.*;
import com.azure.messaging.webpubsub.models.*;
/**
* Publish messages using Azure Web PubSub service SDK
*
*/
public class App
{
public static void main( String[] args )
{
if (args.length != 3) {
System.out.println("Expecting 3 arguments: <connection-string> <hub-name> <message>");
return;
}
WebPubSubServiceClient service = new WebPubSubServiceClientBuilder()
.connectionString(args[0])
.hub(args[1])
.buildClient();
service.sendToAll(args[2], WebPubSubContentType.TEXT_PLAIN);
}
}
The sendToAll() call sends a message to all connected clients in a hub.
To send a message, go to the webpubsub-quickstart-publisher directory and run the project using the following command. Replace the <Web-PubSub-connection-string> with the connection string you copied earlier.
You can see that the subscriber received the message:
Message received: Hello World
Cleanup
You can delete the resources that you created in this quickstart by deleting the resource group that contains them.
az group delete --name myResourceGroup --yes
If you aren't planning to continue using Azure Cloud Shell, you can avoid accumulating costs by deleting the resource group that contains the associated the storage account. The resource group is named cloud-shell-storage-<your-region>. Run the following command, replacing <CloudShellResourceGroup> with the Cloud Shell group name.
az group delete --name <CloudShellResourceGroup> --yes
Caution
Deleting resource groups will delete all resources, including resources created outside the scope of this tutorial.
Next steps
This tutorial provides you with a basic idea of how to connect to the Web PubSub service and publish messages to the connected clients.
Check other tutorials to dive further into how to use the service.