THE MEDIA FOR AI THAT ACTUALLY HELPS.French edition · Understand & take action
The interface is in English. Use cases, skills and articles remain in French.
Microsoft

Pousser des mises à jour en temps réel avec Web PubSub en Java

azure-messaging-webpubsub-java

En bref

Le texte source décrit le SDK Java Azure Web PubSub. L’usage typique est de mettre en place une messagerie WebSocket, des mises à jour en direct, un chat ou une notification poussée du serveur vers le client. La connexion peut passer par `WEB_PUBSUB_CONNECTION_STRING`, `WEB_PUBSUB_ENDPOINT` ou une clé, et `AZURE_TOKEN_CREDENTIALS`. Ce n’est pas le SDK TypeScript `@azure/web-pubsub`. Le langage de référence est Java. Le paquet Maven documenté est `azure-messaging-webpubsub`. Il sert à une messagerie WebSocket, des mises à jour en direct, un chat ou une notification poussée du serveur vers le client.

Ce que ça fait

  • Mettre en place une messagerie WebSocket, des mises à jour en direct, un chat ou une notification poussée du serveur vers le client.
  • La connexion peut passer par `WEB_PUBSUB_CONNECTION_STRING`, `WEB_PUBSUB_ENDPOINT` ou une clé, et `AZURE_TOKEN_CREDENTIALS`.
  • Ce n’est pas le SDK TypeScript `@azure/web-pubsub`.
  • Les variables d’environnement typiques comprennent `AZURE_TOKEN_CREDENTIALS`, `WEB_PUBSUB_CONNECTION_STRING`, `WEB_PUBSUB_ENDPOINT`, `WEB_PUBSUB_ACCESS_KEY`.
  • Les clients documentés comprennent `WebPubSubServiceClient`, `WebPubSubServiceClientBuilder`, `AzureKeyCredential`, `TokenCredential`, `DefaultAzureCredentialBuilder`.
  • L’authentification typique passe par `DefaultAzureCredential`.

Pour qui, et un exemple

Côté Java, les personnes qui poussent des mises à jour en direct ou un chat via Web PubSub, plutôt que via le client JavaScript.

Exemple de demande : « En Java, ouvre un canal Web PubSub pour des notifications serveur-client en WebSocket, via WEB_PUBSUB_ENDPOINT. »

À choisir pour une messagerie WebSocket, des mises à jour en direct, un chat ou une notification poussée, avec le SDK Java Web PubSub. Exemple rédigé par iadujour.fr à partir du SKILL.md, non testé.

Installer

npx skills add microsoft/skills (sélection de la skill dans l’assistant, README).

npx skills add microsoft/skills

Fonctionne avec

  • GitHub Copilot
  • Copilot CLI

Source : README : exemples de « Copilot CLI » et « GitHub Copilot in VS Code » ; l’installation `npx skills add` envoie les fichiers vers le répertoire de l’agent choisi, sans liste exhaustive.

Niveau : Intermédiaire

Suppose un projet de l’éditeur et la maîtrise du SDK ou de la CLI correspondante.

À savoir

Dépôt officiel Microsoft ; le README le présente comme un travail en cours (skills et tests encore enrichis).

Extrait du SKILL.md

La description d’origine, celle que l’agent lit pour décider de charger la skill (en anglais) :

Build real-time web applications with Azure Web PubSub SDK for Java. Use when implementing WebSocket-based messaging, live updates, chat applications, or server-to-client push notifications.

Citée depuis le SKILL.md au commit e7ee58f . Le dossier contient aussi 1 fichier annexe (references/).

Le SKILL.md compte 308 lignes et 23 sections principales :

  • Installation
  • Client Creation
  • With Connection String
  • With Access Key
  • With DefaultAzureCredential
  • Async Client
  • Key Concepts
  • Core Patterns
  • Send to All Connections
  • Send to All with Filter
  • Send to Group
  • Send to Specific Connection
  • Send to User
  • Manage Groups
  • Manage Connections
  • Generate Client Access Token
  • Grant/Revoke Permissions
  • Async Operations
  • Error Handling
  • Environment Variables
  • Client Roles
  • Best Practices
  • Trigger Phrases

Licence : MIT

Vérifiée le 10 novembre 2026 sur : fichier LICENSE du dépôt . Licence déclarée dans le frontmatter : « MIT ». Titulaire : Copyright (c) Microsoft Corporation..

La licence autorise la reprise : le texte intégral du SKILL.md est reproduit ci-dessous, sans modification, avec sa mention de licence.

Texte intégral du SKILL.md

Reproduit sans modification depuis microsoft/skills (commit e7ee58f) , © Microsoft, sous licence MIT (fichier de licence d’origine ).

Afficher le SKILL.md original (308 lignes, en anglais)
---
name: azure-messaging-webpubsub-java
description: Build real-time web applications with Azure Web PubSub SDK for Java. Use when implementing WebSocket-based messaging, live updates, chat applications, or server-to-client push notifications.
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
  package: com.azure:azure-messaging-webpubsub
---

# Azure Web PubSub SDK for Java

Build real-time web applications using the Azure Web PubSub SDK for Java.

## Installation

```xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-messaging-webpubsub</artifactId>
    <version>1.5.0</version>
</dependency>
```

## Client Creation

### With Connection String

```java
import com.azure.messaging.webpubsub.WebPubSubServiceClient;
import com.azure.messaging.webpubsub.WebPubSubServiceClientBuilder;

WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
    .connectionString("<connection-string>")
    .hub("chat")
    .buildClient();
```

### With Access Key

```java
import com.azure.core.credential.AzureKeyCredential;

WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
    .credential(new AzureKeyCredential("<access-key>"))
    .endpoint("<endpoint>")
    .hub("chat")
    .buildClient();
```

### With DefaultAzureCredential

```java
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
    .credential(credential)
    .endpoint("<endpoint>")
    .hub("chat")
    .buildClient();
```

### Async Client

```java
import com.azure.messaging.webpubsub.WebPubSubServiceAsyncClient;

WebPubSubServiceAsyncClient asyncClient = new WebPubSubServiceClientBuilder()
    .connectionString("<connection-string>")
    .hub("chat")
    .buildAsyncClient();
```

## Key Concepts

- **Hub**: Logical isolation unit for connections
- **Group**: Subset of connections within a hub
- **Connection**: Individual WebSocket client connection
- **User**: Entity that can have multiple connections

## Core Patterns

### Send to All Connections

```java
import com.azure.messaging.webpubsub.models.WebPubSubContentType;

// Send text message
client.sendToAll("Hello everyone!", WebPubSubContentType.TEXT_PLAIN);

// Send JSON
String jsonMessage = "{\"type\": \"notification\", \"message\": \"New update!\"}";
client.sendToAll(jsonMessage, WebPubSubContentType.APPLICATION_JSON);
```

### Send to All with Filter

```java
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.util.BinaryData;

BinaryData message = BinaryData.fromString("Hello filtered users!");

// Filter by userId
client.sendToAllWithResponse(
    message,
    WebPubSubContentType.TEXT_PLAIN,
    message.getLength(),
    new RequestOptions().addQueryParam("filter", "userId ne 'user1'"));

// Filter by groups
client.sendToAllWithResponse(
    message,
    WebPubSubContentType.TEXT_PLAIN,
    message.getLength(),
    new RequestOptions().addQueryParam("filter", "'GroupA' in groups and not('GroupB' in groups)"));
```

### Send to Group

```java
// Send to all connections in a group
client.sendToGroup("java-developers", "Hello Java devs!", WebPubSubContentType.TEXT_PLAIN);

// Send JSON to group
String json = "{\"event\": \"update\", \"data\": {\"version\": \"2.0\"}}";
client.sendToGroup("subscribers", json, WebPubSubContentType.APPLICATION_JSON);
```

### Send to Specific Connection

```java
// Send to a specific connection by ID
client.sendToConnection("connectionId123", "Private message", WebPubSubContentType.TEXT_PLAIN);
```

### Send to User

```java
// Send to all connections for a specific user
client.sendToUser("andy", "Hello Andy!", WebPubSubContentType.TEXT_PLAIN);
```

### Manage Groups

```java
// Add connection to group
client.addConnectionToGroup("premium-users", "connectionId123");

// Remove connection from group
client.removeConnectionFromGroup("premium-users", "connectionId123");

// Add user to group (all their connections)
client.addUserToGroup("admin-group", "userId456");

// Remove user from group
client.removeUserFromGroup("admin-group", "userId456");

// Check if user is in group
boolean exists = client.userExistsInGroup("admin-group", "userId456");
```

### Manage Connections

```java
// Check if connection exists
boolean connected = client.connectionExists("connectionId123");

// Close a connection
client.closeConnection("connectionId123");

// Close with reason
client.closeConnection("connectionId123", "Session expired");

// Check if user exists (has any connections)
boolean userOnline = client.userExists("userId456");

// Close all connections for a user
client.closeUserConnections("userId456");

// Close all connections in a group
client.closeGroupConnections("inactive-group");
```

### Generate Client Access Token

```java
import com.azure.messaging.webpubsub.models.GetClientAccessTokenOptions;
import com.azure.messaging.webpubsub.models.WebPubSubClientAccessToken;

// Basic token
WebPubSubClientAccessToken token = client.getClientAccessToken(
    new GetClientAccessTokenOptions());
System.out.println("URL: " + token.getUrl());

// With user ID
WebPubSubClientAccessToken userToken = client.getClientAccessToken(
    new GetClientAccessTokenOptions().setUserId("user123"));

// With roles (permissions)
WebPubSubClientAccessToken roleToken = client.getClientAccessToken(
    new GetClientAccessTokenOptions()
        .setUserId("user123")
        .addRole("webpubsub.joinLeaveGroup")
        .addRole("webpubsub.sendToGroup"));

// With groups to join on connect
WebPubSubClientAccessToken groupToken = client.getClientAccessToken(
    new GetClientAccessTokenOptions()
        .setUserId("user123")
        .addGroup("announcements")
        .addGroup("updates"));

// With custom expiration
WebPubSubClientAccessToken expToken = client.getClientAccessToken(
    new GetClientAccessTokenOptions()
        .setUserId("user123")
        .setExpiresAfter(Duration.ofHours(2)));
```

### Grant/Revoke Permissions

```java
import com.azure.messaging.webpubsub.models.WebPubSubPermission;

// Grant permission to send to a group
client.grantPermission(
    WebPubSubPermission.SEND_TO_GROUP,
    "connectionId123",
    new RequestOptions().addQueryParam("targetName", "chat-room"));

// Revoke permission
client.revokePermission(
    WebPubSubPermission.SEND_TO_GROUP,
    "connectionId123",
    new RequestOptions().addQueryParam("targetName", "chat-room"));

// Check permission
boolean hasPermission = client.checkPermission(
    WebPubSubPermission.SEND_TO_GROUP,
    "connectionId123",
    new RequestOptions().addQueryParam("targetName", "chat-room"));
```

### Async Operations

```java
asyncClient.sendToAll("Async message!", WebPubSubContentType.TEXT_PLAIN)
    .subscribe(
        unused -> System.out.println("Message sent"),
        error -> System.err.println("Error: " + error.getMessage())
    );

asyncClient.sendToGroup("developers", "Group message", WebPubSubContentType.TEXT_PLAIN)
    .doOnSuccess(v -> System.out.println("Sent to group"))
    .doOnError(e -> System.err.println("Failed: " + e))
    .subscribe();
```

## Error Handling

```java
import com.azure.core.exception.HttpResponseException;

try {
    client.sendToConnection("invalid-id", "test", WebPubSubContentType.TEXT_PLAIN);
} catch (HttpResponseException e) {
    System.out.println("Status: " + e.getResponse().getStatusCode());
    System.out.println("Error: " + e.getMessage());
}
```

## Environment Variables

```bash
WEB_PUBSUB_CONNECTION_STRING=Endpoint=https://<resource>.webpubsub.azure.com;AccessKey=...  # Alternative to Entra ID auth
WEB_PUBSUB_ENDPOINT=https://<resource>.webpubsub.azure.com  # Required for AzureKeyCredential or TokenCredential auth
WEB_PUBSUB_ACCESS_KEY=<your-access-key>  # Only required for AzureKeyCredential auth
AZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in production
```

## Client Roles

| Role | Permission |
|------|------------|
| `webpubsub.joinLeaveGroup` | Join/leave any group |
| `webpubsub.sendToGroup` | Send to any group |
| `webpubsub.joinLeaveGroup.<group>` | Join/leave specific group |
| `webpubsub.sendToGroup.<group>` | Send to specific group |

## Best Practices

1. **Use Groups**: Organize connections into groups for targeted messaging
2. **User IDs**: Associate connections with user IDs for user-level messaging
3. **Token Expiration**: Set appropriate token expiration for security
4. **Roles**: Grant minimal required permissions via roles
5. **Hub Isolation**: Use separate hubs for different application features
6. **Connection Management**: Clean up inactive connections

## Trigger Phrases

- "Web PubSub Java"
- "WebSocket messaging Azure"
- "real-time push notifications"
- "server-sent events"
- "chat application backend"
- "live updates broadcasting"
Source. Fiche rédigée par iadujour.fr à partir de : Frontmatter, sections et corps du SKILL.md, README du dépôt. Consultée le 10 novembre 2026. Dépôt : microsoft/skills .
MÊME ÉDITEUR

Autres skills Microsoft : Cloud et infrastructure

Toute la catégorie
MicrosoftCloud et infrastructure

Analyser les ressources Azure inactives et prévalider une suppression

azure-advisor-cost-optimization

Analyse les constats Azure Advisor de la catégorie Cost/IdleResources et prévalide la sûreté d’une suppression, y compris dans le cadre de Service Groups.

Outils : GitHub Copilot, Copilot CLINiveau : Intermédiairemàj 09/11/2026
MicrosoftCloud et infrastructure

Consulter et prioriser les recommandations Azure Advisor

azure-advisor

Sert à consulter Azure Advisor : afficher les recommandations, prioriser les actions, suivre les retraits de service ou mettre à jour un statut.

Outils : GitHub Copilot, Copilot CLINiveau : Intermédiairemàj 09/11/2026
ÉCHANGES

Commentaires.

Un retour d’expérience, une question, une précision sur cette skill ? Les commentaires sont relus avant publication.

Commentaires publiés

Chargement des commentaires…

    Laisser un commentaire

    Charte de modération. Chaque commentaire est relu avant publication. Sont refusés : l’incitation à la haine, les propos injurieux ou discriminatoires, la publicité, le spam et les liens promotionnels, le hors-sujet et les données personnelles d’autrui.