다음을 통해 공유


JavaScript용 Web PubSub 클라이언트 쪽 SDK

참고 항목

여기에 사용된 용어에 대한 자세한 내용은 주요 개념 문서에 설명되어 있습니다.

클라이언트 쪽 SDK는 개발자의 워크플로 속도를 높이는 것을 목표로 합니다. 보다 구체적으로 말하면 다음과 같습니다.

  • 클라이언트 연결 관리 간소화
  • 클라이언트 간 메시지 전송 간소화
  • 의도치 않은 클라이언트 연결 끊김 후 자동으로 다시 시도
  • 연결 끊기에서 복구한 후 수와 순서대로 메시지를 안정적으로 전달합니다.

다이어그램에 표시된 것처럼 클라이언트는 Web PubSub 리소스와 WebSocket 연결을 설정합니다.

Screenshot showing clients establishing WebSocket connection with a Web PubSub resource

시작하기

필수 조건

1. @azure/web-pubsub-client 패키지를 설치합니다.

npm install @azure/web-pubsub-client

2. Web PubSub 리소스로 연결

클라이언트는 Client Access URL을 사용하여 wss://<service_name>.webpubsub.azure.com/client/hubs/<hub_name>?access_token=<token> 패턴을 따르는 서비스에 연결하고 인증합니다. 클라이언트는 몇 가지 방법으로 Client Access URL을 얻을 수 있습니다. 이 빠른 가이드를 위해 표시된 Azure Portal에서 하나를 복사하여 붙여넣을 수 있습니다. (프로덕션의 경우 클라이언트의 Client Access URL은 애플리케이션 서버에서 생성됩니다. 세부 정보 참조 )

Screenshot showing how to get Client Access Url on Azure portal

다이어그램에 표시된 것처럼 클라이언트에는 group1이라는 특정 그룹에 메시지를 보내고 조인할 수 있는 권한이 있습니다.

// Imports the client libray
const { WebPubSubClient } = require("@azure/web-pubsub-client");

// Instantiates the client object
const client = new WebPubSubClient("<client-access-url>");

// Starts the client connection with your Web PubSub resource
await client.start();

// ...
// The client can join/leave groups, send/receive messages to and from those groups all in real-time

3. 그룹 가입

클라이언트는 조인된 그룹에서만 메시지를 받을 수 있습니다. 콜백을 추가하여 메시지를 받을 때 수행할 작업에 대한 논리를 지정할 수 있습니다.

// ...continues the code snippet from above

// Specifies the group to join
let groupName = "group1";

// Registers a listener for the event 'group-message' early before joining a group to not miss messages
client.on("group-message", (e) => {
  console.log(`Received message: ${e.message.data}`);
});

// A client needs to join the group it wishes to receive messages from
await client.joinGroup(groupName);

4. 그룹으로 메시지 보내기

// ...continues the code snippet from above

// Send a message to a joined group
await client.sendToGroup(groupName, "hello world", "text");

// In the Console tab of your developer tools found in your browser, you should see the message printed there.

예제

connected, disconnectedstopped 이벤트 처리

Azure Web PubSub는 connected, disconnectedstopped와 같은 시스템 이벤트를 발생시킵니다. 이벤트 처리기를 등록하여 이벤트가 발생할 때 프로그램이 수행해야 하는 작업을 결정할 수 있습니다.

  1. 클라이언트가 Web PubSub 리소스에 성공적으로 연결되면 connected 이벤트가 트리거됩니다. 이 코드 조각은 단순히 연결 ID를 출력합니다.
client.on("connected", (e) => {
  console.log(`Connection ${e.connectionId} is connected.`);
});
  1. 클라이언트의 연결이 끊어지고 연결을 복구하지 못하면 disconnected 이벤트가 트리거됩니다. 이 코드 조각은 메시지를 출력하기만 하면 됩니다.
client.on("disconnected", (e) => {
  console.log(`Connection disconnected: ${e.message}`);
});
  1. 클라이언트의 연결이 끊어지고 클라이언트가 다시 연결 시도를 중지하면 stopped 이벤트가 트리거됩니다. 이러한 상황은 일반적으로 client.stop()이 호출되거나 autoReconnect가 사용하지 않도록 설정되거나, 지정된 다시 연결 시도 제한에 도달한 후에 발생합니다. 클라이언트를 다시 시작하려면 중지된 이벤트에서 client.start()를 호출할 수 있습니다.
// Registers an event handler for the "stopped" event
client.on("stopped", () => {
  console.log(`Client has stopped`);
});

애플리케이션 서버를 사용하여 프로그래밍 방식으로 Client Access URL을 생성합니다.

프로덕션 환경에서 클라이언트는 일반적으로 애플리케이션 서버에서 Client Access URL을 가져옵니다. 서버는 Web PubSub 리소스에 대한 connection string을 보유하고 서버 쪽 라이브러리 @azure/web-pubsub의 지원을 받아 Client Access URL을 생성합니다.

1. 애플리케이션 서버

이 코드 조각은 애플리케이션 서버가 /negotiate 엔드포인트를 노출하고 Client Access URL을 반환하는 예입니다.

// This code snippet uses the popular Express framework
const express = require('express');
const app = express();
const port = 8080;

// Imports the server library, which is different from the client library
const { WebPubSubServiceClient } = require('@azure/web-pubsub');
const hubName = 'sample_chat';

const serviceClient = new WebPubSubServiceClient("<web-pubsub-connectionstring>", hubName);

// Note that the token allows the client to join and send messages to any groups. It is specified with the "roles" option.
app.get('/negotiate', async (req, res) => {
  let token = await serviceClient.getClientAccessToken({roles: ["webpubsub.joinLeaveGroup", "webpubsub.sendToGroup"] });
  res.json({
    url: token.url
  });
});

app.listen(port, () => console.log(`Application server listening at http://localhost:${port}/negotiate`));

2. 클라이언트 쪽

const { WebPubSubClient } = require("@azure/web-pubsub-client")

const client = new WebPubSubClient({
  getClientAccessUrl: async () => {
    let value = await (await fetch(`/negotiate`)).json();
    return value.url;
  }
});

await client.start();

참고 항목

이 샘플의 전체 코드를 보려면 samples-browser를 참조하세요.


클라이언트는 애플리케이션 서버 또는 조인된 그룹의 메시지를 사용합니다.

클라이언트는 콜백을 추가하여 애플리케이션 서버 또는 그룹의 메시지를 사용할 수 있습니다.

// Registers a listener for the "server-message". The callback is invoked when your application server sends message to the connectionID, to or broadcast to all connections.
client.on("server-message", (e) => {
  console.log(`Received message ${e.message.data}`);
});

// Registers a listener for the "group-message". The callback is invoked when the client receives a message from the groups it has joined.
client.on("group-message", (e) => {
    console.log(`Received message from ${e.message.group}: ${e.message.data}`);
});

참고 항목

group-message 이벤트의 경우 클라이언트는 조인한 그룹에서 메시지를 받을 수 있습니다.

다시 조인 실패 처리

클라이언트의 연결이 끊어지고 복구에 실패하면 모든 그룹 컨텍스트가 Web PubSub 리소스에서 정리됩니다. 즉, 클라이언트는 다시 연결할 때 그룹에 다시 조인해야 합니다. 기본적으로 클라이언트에는 autoRejoinGroup 옵션이 사용하도록 설정되어 있습니다.

그렇지만 autoRejoinGroup 제한을 인식해야 합니다.

  • 클라이언트는 서버 쪽 코드가 아닌 클라이언트 코드에 의해 조인된 그룹만 다시 조인할 수 있습니다.
  • "그룹 다시 조인" 작업은 여러 가지 이유로 인해 실패할 수 있습니다. 예를 들어 클라이언트에는 그룹에 조인할 수 있는 권한이 없을 수 있습니다. 이러한 경우 이 오류를 처리하기 위해 콜백을 추가해야 합니다.
// By default autoRejoinGroups=true. You can disable it by setting to false.
const client = new WebPubSubClient("<client-access-url>", { autoRejoinGroups: true });

// Registers a listener to handle "rejoin-group-failed" event
client.on("rejoin-group-failed", e => {
  console.log(`Rejoin group ${e.group} failed: ${e.error}`);
})

재시도

기본적으로 client.joinGroup(), client.leaveGroup(), client.sendToGroup(), client.sendEvent() 등의 작업은 3번 다시 시도됩니다. messageRetryOptions를 통해 구성할 수 있습니다. 모든 다시 시도가 실패하면 오류가 throw됩니다. Web PubSub 서비스가 작업을 중복 제거할 수 있도록 이전 다시 시도와 동일한 ackId를 전달하여 계속 다시 시도할 수 있습니다.

try {
  await client.joinGroup(groupName);
} catch (err) {
  let id = null;
  if (err instanceof SendMessageError) {
    id = err.ackId;
  }
  await client.joinGroup(groupName, {ackId: id});
}

JavaScript 번들

브라우저에서 이 클라이언트 라이브러리를 사용하려면 번들러를 사용해야 합니다. 번들을 만드는 방법에 대한 자세한 내용은 번들 설명서를 참조하세요.

문제 해결

로그 사용 설정

다음 환경 변수를 설정하여 이 라이브러리를 사용할 때 디버그 로그를 볼 수 있습니다.

export AZURE_LOG_LEVEL=verbose

로그를 사용하는 방법에 대한 자세한 내용은 @azure/logger package docs를 참조하세요.

라이브 추적

Azure Portal의 라이브 추적 도구를 사용하여 Web PubSub 리소스를 통해 라이브 메시지 트래픽을 검사합니다.