다음을 통해 공유


Azure Web PubSub용 JavaScript SDK

Azure Web PubSub 서비스는 개발자가 실시간 기능 및 게시-구독 패턴으로 웹 애플리케이션을 쉽게 빌드할 수 있도록 도와주는 Azure 관리형 서비스입니다. 서버와 클라이언트 간 또는 클라이언트 간에 실시간 게시-구독 메시징이 필요한 시나리오는 Azure Web PubSub 서비스를 사용할 수 있습니다. 서버에서 폴링하거나 HTTP 요청을 제출해야 하는 기존의 실시간 기능도 Azure Web PubSub 서비스를 사용할 수 있습니다.

JavaScript에는 서비스 클라이언트 라이브러리와 빠른 미들웨어의 두 가지 라이브러리가 제공됩니다. 다음 섹션에는 이러한 라이브러리에 대한 자세한 정보가 포함되어 있습니다.

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

또는 WebPubSubServiceClient 사용하여 인증

  1. @azure/identity 종속성 설치
npm install @azure/identity
  1. 사용할 소스 코드를 업데이트합니다.DefaultAzureCredential
const {
  WebPubSubServiceClient,
  AzureKeyCredential,
} = require("@azure/web-pubsub");

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

예시

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

허브의 모든 연결에 메시지 브로드캐스트

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

그룹의 모든 연결에 메시지 보내기

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

서비스 클라이언트 문제 해결

로그 활성화

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

  • Azure Web PubSub 클라이언트 라이브러리에서 디버그 로그 가져오기
export AZURE_LOG_LEVEL=verbose

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

라이브 추적

Web PubSub 서비스 포털에서 라이브 추적 을 사용하여 라이브 트래픽을 봅니다.

Express용 Azure Web PubSub CloudEvents 처리기

WebSocket 연결이 연결되면 Web PubSub 서비스는 연결 수명 주기 및 메시지를 CloudEvents 형식의 이벤트로 변환합니다. 이 라이브러리는 아래 다이어그램과 같이 WebSocket 연결의 수명 주기 및 메시지를 나타내는 이벤트를 처리하는 빠른 미들웨어를 제공합니다.

오버플로 다이어그램은 이벤트 처리기 미들웨어를 사용하는 오버플로를 보여 줍니다.

소스 코드 | 패키지(NPM) | API 참조 설명서 | 제품 설명서 | 샘플

시작하기

현재 지원되는 환경

필수 조건

  • Azure 구독.
  • 기존 Azure Web PubSub 엔드포인트입니다.

1. 패키지 설치 @azure/web-pubsub-express

npm install @azure/web-pubsub-express

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

Express 예제

connect 요청 처리 및 할당<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}`
  )
);

지정된 엔드포인트만 허용

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

사용자 지정 이벤트 처리기 경로 설정

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

연결 상태 설정 및 읽기

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

Troubleshooting

로그 활성화

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

  • Azure Web PubSub 클라이언트 라이브러리에서 디버그 로그 가져오기
export AZURE_LOG_LEVEL=verbose

로그를 사용하도록 설정하는 방법에 대한 자세한 지침은 @azure/로거 패키지 문서를 참조하세요.

라이브 추적

Web PubSub 서비스 포털에서 라이브 추적 을 사용하여 라이브 트래픽을 봅니다.

다음 단계

다음 리소스를 사용하여 사용자 고유의 애플리케이션 빌드를 시작합니다.