Compartir vía


SDK de JavaScript para Azure Web PubSub

Azure Web PubSub es un servicio administrado de Azure que ayuda a los desarrolladores a compilar fácilmente aplicaciones web con características en tiempo real y patrón de publicación-suscripción. Cualquier escenario que requiera mensajería de publicación y suscripción en tiempo real entre el servidor y los clientes o entre clientes, puede usar el servicio Azure Web PubSub. Las características tradicionales en tiempo real que a menudo requieren tener que sondear desde el servidor o enviar solicitudes HTTP, también pueden usar el servicio Azure Web PubSub.

Hay dos bibliotecas que se ofrecen para JavaScript: la biblioteca cliente de servicio y el middleware express. Las secciones siguientes contienen más información sobre estas bibliotecas.

Biblioteca cliente del servicio Azure Web PubSub para JavaScript

Puede usar esta biblioteca en el lado del servidor de aplicaciones para administrar las conexiones de cliente de WebSocket, como se muestra en el diagrama siguiente:

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

  • Enviar mensajes a centros y grupos.
  • Enviar mensajes a determinados usuarios y conexiones.
  • Organizar usuarios y conexiones en grupos.
  • Cerrar conexiones.
  • Conceder, revocar y comprobar permisos para una conexión existente.

Código fuente | Paquete (NPM) | Documentación de referencia de API | Documentación del producto | Ejemplos

Introducción

Entornos admitidos actualmente

Requisitos previos

1. Instale el paquete @azure/web-pubsub.

npm install @azure/web-pubsub

2. Cree y autentique de WebPubSubServiceClient.

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

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

También puede autenticar WebPubSubServiceClient mediante un punto de conexión y un AzureKeyCredential:

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

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

O autentíquelo WebPubSubServiceClient mediante el identificador de Entra de Microsoft

  1. Instale la dependencia @azure/identity
npm install @azure/identity
  1. Actualización del código fuente para usar DefaultAzureCredential:
const {
  WebPubSubServiceClient,
  AzureKeyCredential,
} = require("@azure/web-pubsub");

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

Ejemplos

Obtener el token de acceso para que un cliente inicie la conexión de 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

Difunde mensajes a todas las conexiones en un concentrador

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);

Envía mensajes a todas las conexiones en un grupo

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);

Envía mensajes a todas las conexiones para un usuario

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);

Comprobación de si el grupo tiene alguna conexión

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>");

Acceso a la respuesta HTTP sin formato para una operación

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 });

Solución de problemas del cliente de servicio

Habilitamiento de registros

Puede establecer la siguiente variable de entorno para obtener los registros de depuración cuando se usa esta biblioteca.

  • Obtención de registros de depuración de la biblioteca cliente de Azure Web PubSub
export AZURE_LOG_LEVEL=verbose

Para obtener instrucciones más detalladas sobre cómo habilitar los registros, consulte los documentos del paquete @azure/logger.

Seguimiento en vivo

Use Seguimiento en vivo desde el portal del servicio Web PubSub para ver el tráfico en directo.

Controladores de CloudEvents de Azure Web PubSub para Express

Cuando se conecta una conexión de WebSocket, el servicio PubSub web transforma el ciclo de vida de la conexión y los mensajes en eventos en formato CloudEvents. Esta biblioteca proporciona un middleware express para controlar eventos que representan el ciclo de vida y los mensajes de la conexión webSocket, como se muestra en el diagrama siguiente:

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

Código fuente | Paquete (NPM) | Documentación de referencia de API | Documentación del producto | Ejemplos

Introducción

Entornos admitidos actualmente

Requisitos previos

1. Instale el paquete @azure/web-pubsub-express.

npm install @azure/web-pubsub-express

2. Cree 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}`
  )
);

Ejemplos rápidos

Control de la solicitud connect y asignación de <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}`
  )
);

Permitir solo los puntos de conexión especificados

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}`
  )
);

Establecer la ruta de acceso del controlador de eventos personalizado

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}`
  )
);

Establecer y leer el estado de conexión

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}`
  )
);

Solucionar problemas

Habilitamiento de registros

Puede establecer la siguiente variable de entorno para obtener los registros de depuración cuando se usa esta biblioteca.

  • Obtención de registros de depuración de la biblioteca cliente de Azure Web PubSub
export AZURE_LOG_LEVEL=verbose

Para instrucciones más detalladas sobre cómo habilitar los registros, consulte los documentos del paquete @azure/logger.

Seguimiento en vivo

Use Seguimiento en vivo desde el portal del servicio Web PubSub para ver el tráfico en directo.

Pasos siguientes

Use estos recursos para empezar a compilar su propia aplicación: