Partilhar via


SDK de JavaScript para Azure Web PubSub

O serviço Azure Web PubSub é um serviço gerido pelo Azure que ajuda os programadores a construir facilmente aplicações web com funcionalidades em tempo real e padrão de publicação-subscrição. Qualquer cenário que exija mensagens de publicação-subscrição em tempo real entre servidor e clientes ou entre clientes pode usar o serviço Azure Web PubSub. Funcionalidades tradicionais em tempo real, que frequentemente requerem sondagens do servidor ou submissão de pedidos HTTP, também podem usar o serviço Azure Web PubSub.

Existem duas bibliotecas disponíveis para JavaScript: a biblioteca cliente do serviço e o middleware Express. As secções seguintes contêm mais informações sobre estas bibliotecas.

Biblioteca de cliente de serviço Azure Web PubSub para JavaScript

Pode usar esta biblioteca no lado do seu servidor de aplicações para gerir as ligações do cliente WebSocket, como mostrado no diagrama abaixo:

O diagrama de sobrecarga mostra a sobrecarga ao utilizar a biblioteca de cliente de serviço.

  • Envia mensagens para hubs e grupos.
  • Envie mensagens a utilizadores e ligações específicas.
  • Organizar utilizadores e ligações em grupos.
  • Ligações próximas
  • Conceder, revogar e verificar permissões para uma ligação existente

Código-fonte | Pacote (NPM) | Documentação | Documentação | do produtoExemplos

Como Começar

Ambientes atualmente suportados

Pré-requisitos

  • Uma assinatura do Azure.
  • Uma instância existente do serviço Azure Web PubSub.

1. Instalar o @azure/web-pubsub pacote

npm install @azure/web-pubsub

2. Criar e autenticar um WebPubSubServiceClient

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

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

Também pode autenticar o WebPubSubServiceClient usando um endpoint e um AzureKeyCredential:

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

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

Ou autenticar o WebPubSubServiceClient usando o Microsoft Entra ID

  1. Instalar a @azure/identity dependência
npm install @azure/identity
  1. Atualize o código-fonte para usar DefaultAzureCredential:
const {
  WebPubSubServiceClient,
  AzureKeyCredential,
} = require("@azure/web-pubsub");

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

Examples

Obtenha o token de acesso para um cliente iniciar a ligação 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

Transmitir mensagens para todas as ligações num 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);

Enviar mensagens para todas as ligações de um 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);

Enviar mensagens para todas as ligações de um utilizador

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

Verifica se o grupo tem alguma ligação

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

Acede à resposta HTTP bruta para uma operação

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

Resolução de problemas com clientes de serviço

Ativar registos

Pode definir a seguinte variável de ambiente para obter os registos de depuração ao usar esta biblioteca.

  • Obter registos de depuração da biblioteca cliente Azure Web PubSub
export AZURE_LOG_LEVEL=verbose

Para obter instruções mais detalhadas sobre como habilitar logs, você pode consultar os documentos do pacote @azure/logger.

Live Trace

Utilize o Live Trace do portal de serviço Web PubSub para visualizar o tráfego em tempo real.

Manipuladores Azure Web PubSub CloudEvents para Express

Quando uma ligação WebSocket se conecta, o serviço Web PubSub transforma o ciclo de vida da ligação e as mensagens em eventos no formato CloudEvents. Esta biblioteca fornece um middleware expresso para gerir eventos que representam o ciclo de vida e as mensagens da ligação WebSocket, conforme mostrado no diagrama abaixo:

O diagrama de overflow mostra o overflow ao usar o middleware do gestor de eventos.

Código-fonte | Pacote (NPM) | Documentação | Documentação | do produtoExemplos

Como Começar

Ambientes atualmente suportados

Pré-requisitos

  • Uma assinatura do Azure.
  • Um endpoint Azure Web PubSub existente.

1. Instalar o @azure/web-pubsub-express pacote

npm install @azure/web-pubsub-express

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

Exemplos expressos

Tratar do connect pedido e atribuir <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 apenas endpoints 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}`
  )
);

Defina o caminho do gestor 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}`
  )
);

Definir e ler o estado da ligação

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

Solução de problemas

Ativar registos

Pode definir a seguinte variável de ambiente para obter os registos de depuração ao usar esta biblioteca.

  • Obter registos de depuração da biblioteca cliente Azure Web PubSub
export AZURE_LOG_LEVEL=verbose

Para instruções mais detalhadas sobre como ativar logs, consulte a documentação do pacote @azure/logger.

Live Trace

Utilize o Live Trace do portal de serviço Web PubSub para visualizar o tráfego em tempo real.

Próximos passos

Use estes recursos para começar a criar seu próprio aplicativo: