Condividi tramite


JavaScript SDK per PubSub Web di Azure

Il servizio Web PubSub di Azure è un servizio gestito da Azure che consente agli sviluppatori di creare facilmente applicazioni Web con funzionalità in tempo reale e modello di pubblicazione-sottoscrizione. Qualsiasi scenario che richiede la messaggistica di pubblicazione-sottoscrizione in tempo reale tra server e client o tra i client può usare il servizio Web PubSub di Azure. Le funzionalità tradizionali in tempo reale che spesso richiedono il polling dal server o l'invio di richieste HTTP possono usare anche il servizio PubSub Web di Azure.

Sono disponibili due librerie per JavaScript: la libreria client del servizio e il middleware rapido. Le sezioni seguenti contengono altre informazioni su queste librerie.

Libreria client del servizio Web PubSub di Azure per JavaScript

È possibile usare questa libreria sul lato server dell'app per gestire le connessioni client WebSocket, come illustrato nel diagramma seguente:

The overflow diagram shows the overflow of using the service client library.

  • Inviare messaggi a hub e gruppi.
  • Inviare messaggi a utenti e connessioni specifici.
  • Organizzare utenti e connessioni in gruppi.
  • Chiudere le connessioni
  • Concedere, revocare e controllare le autorizzazioni per una connessione esistente

Esempi della documentazione | | di riferimento dell'API del pacchetto del codice | sorgente (NPM) |

Introduzione

Ambienti attualmente supportati

Prerequisiti

1. Installare il @azure/web-pubsub pacchetto

npm install @azure/web-pubsub

2. Creare ed autenticare un WebPubSubServiceClient

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

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

È anche possibile autenticare WebPubSubServiceClient usando un endpoint e un AzureKeyCredentialoggetto :

const {
  WebPubSubServiceClient,
  AzureKeyCredential,
} = require("@azure/web-pubsub");

const key = new AzureKeyCredential("<Key>");
const serviceClient = new WebPubSubServiceClient(
  "<Endpoint>",
  key,
  "<hubName>"
);

In alternativa, autenticare l'oggetto WebPubSubServiceClient utilizzando Microsoft Entra ID

  1. Installare la @azure/identity dipendenza
npm install @azure/identity
  1. Aggiornare il codice sorgente per usare DefaultAzureCredential:
const {
  WebPubSubServiceClient,
  AzureKeyCredential,
} = require("@azure/web-pubsub");

const key = new DefaultAzureCredential();
const serviceClient = new WebPubSubServiceClient(
  "<Endpoint>",
  key,
  "<hubName>"
);

Esempi

Ottenere il token di accesso per un client per avviare la connessione WebSocket

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

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

// Get the access token for the WebSocket client connection to use
let token = await serviceClient.getClientAccessToken();

// Or get the access token and assign the client a userId
token = await serviceClient.getClientAccessToken({ userId: "user1" });

// return the token to the WebSocket client

Trasmettere messaggi a tutte le connessioni in un hub

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

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

// Send a JSON message
await serviceClient.sendToAll({ message: "Hello world!" });

// Send a plain text message
await serviceClient.sendToAll("Hi there!", { contentType: "text/plain" });

// Send a binary message
const payload = new Uint8Array(10);
await serviceClient.sendToAll(payload.buffer);

Inviare messaggi a tutte le connessioni in un gruppo

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

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

const groupClient = serviceClient.group("<groupName>");

// Add user to the group
await groupClient.addUser("user1");

// Send a JSON message
await groupClient.sendToAll({ message: "Hello world!" });

// Send a plain text message
await groupClient.sendToAll("Hi there!", { contentType: "text/plain" });

// Send a binary message
const payload = new Uint8Array(10);
await groupClient.sendToAll(payload.buffer);

Inviare messaggi a tutte le connessioni per un utente

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

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

// Send a JSON message
await serviceClient.sendToUser("user1", { message: "Hello world!" });

// Send a plain text message
await serviceClient.sendToUser("user1", "Hi there!", {
  contentType: "text/plain",
});

// Send a binary message
const payload = new Uint8Array(10);
await serviceClient.sendToUser("user1", payload.buffer);

Controllare se il gruppo dispone di una connessione

const { WebPubSubServiceClient } = require("@azure/web-pubsub");
const WebSocket = require("ws");

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

const groupClient = serviceClient.group("<groupName>");

// close all the connections in the group
await groupClient.closeAllConnections({ reason: "<closeReason>" });

// check if the group has any connections
const hasConnections = await serviceClient.groupExists("<groupName>");

Accedere alla risposta HTTP non elaborata per un'operazione

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

function onResponse(rawResponse: FullOperationResponse): void {
  console.log(rawResponse);
}
const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);
await serviceClient.sendToAll({ message: "Hello world!" }, { onResponse });

Risoluzione dei problemi del client del servizio

Abilitare i log

È possibile impostare la variabile di ambiente seguente per ottenere i log di debug quando si usa questa libreria.

  • Recupero dei log di debug dalla libreria client PubSub di Azure
export AZURE_LOG_LEVEL=verbose

Per istruzioni più dettagliate su come abilitare i log, è possibile esaminare la documentazione del pacchetto @azure/logger.

Traccia in tempo reale

Usare Live Trace dal portale del servizio Web PubSub per visualizzare il traffico live.

Gestori di CloudEventSub di Azure Web PubSub per Express

Quando una connessione WebSocket si connette, il servizio Web PubSub trasforma il ciclo di vita della connessione e i messaggi in eventi in formato CloudEvents. Questa libreria fornisce un middleware rapido per gestire gli eventi che rappresentano il ciclo di vita e i messaggi della connessione WebSocket, come illustrato nel diagramma seguente:

The overflow diagram shows the overflow of using the event handler middleware.

Esempi della documentazione | | di riferimento dell'API del pacchetto del codice | sorgente (NPM) |

Introduzione

Ambienti attualmente supportati

Prerequisiti

1. Installare il @azure/web-pubsub-express pacchetto

npm install @azure/web-pubsub-express

2. Creare un WebPubSubEventHandler

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat");

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

Esempi express

Gestire la connect richiesta e assegnare <userId>

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  handleConnect: (req, res) => {
    // auth the connection and set the userId of the connection
    res.success({
      userId: "<userId>",
    });
  },
  allowedEndpoints: ["https://<yourAllowedService>.webpubsub.azure.com"],
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

Consenti solo endpoint specificati

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  allowedEndpoints: [
    "https://<yourAllowedService1>.webpubsub.azure.com",
    "https://<yourAllowedService2>.webpubsub.azure.com",
  ],
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

Impostare il percorso del gestore eventi personalizzato

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  path: "/customPath1",
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  // Azure WebPubSub Upstream ready at http://localhost:3000/customPath1
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

Impostare e leggere lo stato della connessione

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");

const handler = new WebPubSubEventHandler("chat", {
  handleConnect(req, res) {
    // You can set the state for the connection, it lasts throughout the lifetime of the connection
    res.setState("calledTime", 1);
    res.success();
  },
  handleUserEvent(req, res) {
    var calledTime = req.context.states.calledTime++;
    console.log(calledTime);
    // You can also set the state here
    res.setState("calledTime", calledTime);
    res.success();
  },
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

Risoluzione dei problemi

Abilitare i log

È possibile impostare la variabile di ambiente seguente per ottenere i log di debug quando si usa questa libreria.

  • Recupero dei log di debug dalla libreria client PubSub di Azure
export AZURE_LOG_LEVEL=verbose

Per istruzioni più dettagliate su come abilitare i log, vedere la documentazione sui pacchetti @azure/logger.

Traccia in tempo reale

Usare Live Trace dal portale del servizio Web PubSub per visualizzare il traffico live.

Passaggi successivi

Usare queste risorse per iniziare a creare un'applicazione personalizzata: