JavaScript용 Azure Web PubSub 서비스 클라이언트 라이브러리 - 버전 1.1.1
Azure Web PubSub 서비스는 개발자가 실시간 기능 및 게시-구독 패턴을 사용하여 웹 애플리케이션을 쉽게 빌드할 수 있도록 도와주는 Azure 관리형 서비스입니다. 서버와 클라이언트 간 또는 클라이언트 간에 실시간 게시-구독 메시징이 필요한 시나리오에서는 Azure Web PubSub 서비스를 사용할 수 있습니다. 서버에서 폴링하거나 HTTP 요청을 제출해야 하는 경우가 많은 기존의 실시간 기능도 Azure Web PubSub 서비스를 사용할 수 있습니다.
아래 다이어그램과 같이 앱 서버 쪽에서 이 라이브러리를 사용하여 WebSocket 클라이언트 연결을 관리할 수 있습니다.
.
- 허브 및 그룹에 메시지를 보냅니다.
- 특정 사용자 및 연결에 메시지를 보냅니다.
- 사용자와 연결을 그룹으로 구성합니다.
- 연결 종료
- 기존 연결에 대한 권한 부여, 철회 및 확인
여기에 사용된 용어에 대한 자세한 내용은 주요 개념 섹션에 설명되어 있습니다.
소스 코드 | 패키지(NPM) | API 참조 설명서 | 제품 설명서 | 샘플
시작
현재 지원되는 환경
필수 구성 요소
- Azure 구독.
- 기존 Azure Web PubSub 서비스 인스턴스.
1. @azure/web-pubsub
패키지 설치
npm install @azure/web-pubsub
2. WebPubSubServiceClient 만들기 및 인증
const { WebPubSubServiceClient } = require("@azure/web-pubsub");
const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");
엔드포인트와 AzureKeyCredential
을 사용하여 WebPubSubServiceClient
를 인증할 수도 있습니다.
const { WebPubSubServiceClient, AzureKeyCredential } = require("@azure/web-pubsub");
const key = new AzureKeyCredential("<Key>");
const serviceClient = new WebPubSubServiceClient("<Endpoint>", key, "<hubName>");
또는 Azure Active Directory를 WebPubSubServiceClient
사용하여 를 인증합니다.
@azure/identity
종속성을 설치합니다.
npm install @azure/identity
DefaultAzureCredential
을 사용하여 소스 코드 업데이트:
const { WebPubSubServiceClient, AzureKeyCredential } = require("@azure/web-pubsub");
const { DefaultAzureCredential } = require("@azure/identity");
const key = new DefaultAzureCredential();
const serviceClient = new WebPubSubServiceClient("<Endpoint>", key, "<hubName>");
주요 개념
연결
연결: 클라이언트 또는 클라이언트 연결이라고도 하는 연결은 Web PubSub 서비스에 연결된 개별 WebSocket 연결을 나타냅니다. 성공적으로 연결되면 Web PubSub 서비스에서 고유한 연결 ID를 이 연결에 할당합니다.
허브
허브는 클라이언트 연결 집합에 대한 논리적 개념입니다. 일반적으로 하나의 목적에 대해 하나의 허브를 사용합니다(예: 채팅 허브 또는 알림 허브). 클라이언트 연결이 만들어지면 허브에 연결되고 수명 동안 해당 허브에 속합니다. 애플리케이션마다 서로 다른 허브 이름을 사용하여 하나의 Azure Web PubSub 서비스를 공유할 수 있습니다.
그룹
그룹은 허브에 대한 연결의 하위 집합입니다. 그룹에 클라이언트 연결을 추가하거나 원하는 경우 그룹에서 클라이언트 연결을 제거할 수 있습니다. 예를 들어 클라이언트가 채팅방에 참가하거나 채팅방에서 나가면 이 채팅방이 그룹일 수 있습니다. 클라이언트는 여러 그룹에 참가할 수 있으며, 한 그룹에 여러 클라이언트가 포함될 수 있습니다.
사용자
Web PubSub에 대한 연결은 한 사용자에 속할 수 있습니다. 단일 사용자가 여러 디바이스 또는 여러 브라우저 탭에서 연결된 경우와 같이 사용자에게 여러 연결이 있을 수 있습니다.
메시지
클라이언트가 연결되면 메시지를 업스트림 애플리케이션으로 보내거나 WebSocket 연결을 통해 업스트림 애플리케이션에서 메시지를 받을 수 있습니다.
예제
클라이언트가 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" });
// Or get the access token that the client will join group GroupA when it connects using the access token
token = await serviceClient.getClientAccessToken({ userId: "user1", groups: [ "GroupA" ] });
// return the token to the WebSocket client
허브의 모든 연결에 메시지 브로드캐스트
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);
OData 필터 구문을 사용하여 허브의 모든 연결에 메시지 보내기
구문에 대한 filter
자세한 내용은 Azure Web PubSub에 대한 OData 필터 구문을 참조하세요.
const { WebPubSubServiceClient, odata } = require("@azure/web-pubsub");
const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");
// Send a JSON message to anonymous connections
await serviceClient.sendToAll(
{ message: "Hello world!" },
{ filter: "userId eq null" }
);
// Send a text message to connections in groupA but not in groupB
const groupA = 'groupA';
const groupB = 'groupB';
await serviceClient.sendToAll(
"Hello world!",
{
contentType: "text/plain",
// use plain text "'groupA' in groups and not('groupB' in groups)"
// or use the odata helper method
filter: odata`${groupA} in groups and not(${groupB} in groups)`
});
그룹의 모든 연결에 메시지 보내기
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);
사용자의 모든 연결에 메시지 보내기
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);
그룹에 연결이 있는지 확인
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>");
작업에 대한 원시 HTTP 응답에 액세스
const { WebPubSubServiceClient } = require("@azure/web-pubsub");
function onResponse(rawResponse) {
console.log(rawResponse);
}
const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");
await serviceClient.sendToAll({ message: "Hello world!" }, { onResponse });
문제 해결
로그 사용 설정
다음 환경 변수를 설정하여 이 라이브러리를 사용할 때 디버그 로그를 볼 수 있습니다.
- SignalR 클라이언트 라이브러리에서 디버그 로그 가져오기
export AZURE_LOG_LEVEL=verbose
로그를 사용하는 방법에 대한 자세한 내용은 @azure/logger package docs를 참조하세요.
라이브 추적
Web PubSub 서비스 포털에서 라이브 추적을 사용하여 실시간 트래픽을 확인합니다.
다음 단계
이 라이브러리를 사용하는 방법에 대한 자세한 예제는 샘플 디렉터리를 참조하세요.
참여
이 라이브러리에 기여하려면 기여 가이드 를 참조하여 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.
관련된 프로젝트
Azure SDK for JavaScript
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기