azure-communication-chat-java
microsoft/skills
Azure Communication Services Chat Java SDK를 사용하여 스레드 관리, 메시징, 참가자, 읽음 확인 기능을 갖춘 실시간 채팅 애플리케이션을 구축하세요.
...모든 것을 확장하십시오Azure Communication Chat (Java)
스레드 관리, 메시징, 참가자, 읽음 확인 기능을 갖춘 실시간 채팅 애플리케이션을 구축하세요.
설치
com.azure
azure-communication-chat
1.6.0
클라이언트 생성
import com.azure.communication.chat.ChatClient;
import com.azure.communication.chat.ChatClientBuilder;
import com.azure.communication.chat.ChatThreadClient;
import com.azure.communication.common.CommunicationTokenCredential;
// ChatClient에는 CommunicationTokenCredential(사용자 액세스 토큰)이 필요합니다.
String endpoint = "https://.communication.azure.com";
String userAccessToken = "";
CommunicationTokenCredential credential = new CommunicationTokenCredential(userAccessToken);
ChatClient chatClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
// 비동기 클라이언트
ChatAsyncClient chatAsyncClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildAsyncClient();
핵심 개념
| 클래스 | 목적 |
|---|---|
ChatClient |
채팅 스레드 생성/삭제, 스레드 클라이언트 가져오기 |
ChatThreadClient |
스레드 내의 작업(메시지, 참가자, 수신 확인) |
채팅 참가자 |
표시 이름이 있는 채팅 스레드의 사용자 |
ChatMessage |
메시지 내용, 유형, 발신자 정보, 타임스탬프 |
채팅 메시지 읽음 확인 |
참가자별 읽음 확인 추적 |
채팅 스레드 생성
import com.azure.communication.chat.models.*;
import com.azure.communication.common.CommunicationUserIdentifier;
import java.util.ArrayList;
import java.util.List;
// 참가자 정의
List participants = new ArrayList<>();
ChatParticipant participant1 = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier(""))
.setDisplayName("Alice");
ChatParticipant participant2 = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier(""))
.setDisplayName("Bob");
participants.add(participant1);
participants.add(participant2);
// 채팅 스레드 생성
CreateChatThreadOptions options = new CreateChatThreadOptions("프로젝트 토론")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(options);
String threadId = result.getChatThread().getId();
// 작업을 위한 스레드 클라이언트 가져오기
ChatThreadClient threadClient = chatClient.getChatThreadClient(threadId);
메시지 보내기
// 텍스트 메시지 전송
SendChatMessageOptions messageOptions = new SendChatMessageOptions()
.setContent("안녕하세요, 팀원 여러분!")
.setSenderDisplayName("Alice")
.setType(ChatMessageType.TEXT);
SendChatMessageResult sendResult = threadClient.sendMessage(messageOptions);
String messageId = sendResult.getId();
// HTML 메시지 보내기
SendChatMessageOptions htmlOptions = new SendChatMessageOptions()
.setContent("중요: 오후 3시에 회의")
.setType(ChatMessageType.HTML);
threadClient.sendMessage(htmlOptions);
메시지 가져오기
import com.azure.core.util.paging.PagedIterable;
// 모든 메시지 나열
PagedIterable messages = threadClient.listMessages();
for (ChatMessage message : messages) {
System.out.println("ID: " + message.getId());
System.out.println("유형: " + message.getType());
System.out.println("내용: " + message.getContent().getMessage());
System.out.println("보낸 사람: " + message.getSenderDisplayName());
System.out.println("작성 일시: " + message.getCreatedOn());
// 수정 또는 삭제 여부 확인
if (message.getEditedOn() != null) {
System.out.println("수정일: " + message.getEditedOn());
}
if (message.getDeletedOn() != null) {
System.out.println("삭제됨: " + message.getDeletedOn());
}
}
// 특정 메시지 가져오기
ChatMessage message = threadClient.getMessage(messageId);
메시지 업데이트 및 삭제
// 메시지 업데이트
UpdateChatMessageOptions updateOptions = new UpdateChatMessageOptions()
.setContent("업데이트된 메시지 내용");
threadClient.updateMessage(messageId, updateOptions);
// 메시지 삭제
threadClient.deleteMessage(messageId);
참가자 관리
// 참가자 목록 가져오기
PagedIterable participants = threadClient.listParticipants();
for (ChatParticipant participant : participants) {
CommunicationUserIdentifier user =
(CommunicationUserIdentifier) participant.getCommunicationIdentifier();
System.out.println("사용자: " + user.getId());
System.out.println("표시 이름: " + participant.getDisplayName());
}
// 참가자 추가
List newParticipants = new ArrayList<>();
newParticipants.add(new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier(""))
.setDisplayName("Charlie")
.setShareHistoryTime(OffsetDateTime.now().minusDays(7))); // 지난 7일간의 기록 공유
threadClient.addParticipants(newParticipants);
// 참가자 제거
CommunicationUserIdentifier userToRemove = new CommunicationUserIdentifier("");
threadClient.removeParticipant(userToRemove);
읽음 확인
// 읽음 확인 보내기
threadClient.sendReadReceipt(messageId);
// 읽음 확인 받기
PagedIterable receipts = threadClient.listReadReceipts();
for (ChatMessageReadReceipt receipt : receipts) {
System.out.println("메시지 ID: " + receipt.getChatMessageId());
System.out.println("읽은 사람: " + receipt.getSenderCommunicationIdentifier());
System.out.println("읽은 시간: " + receipt.getReadOn());
}
입력 알림
import com.azure.communication.chat.models.TypingNotificationOptions;
// 입력 중 알림 보내기
TypingNotificationOptions typingOptions = new TypingNotificationOptions()
.setSenderDisplayName("Alice");
threadClient.sendTypingNotificationWithResponse(typingOptions, Context.NONE);
// 간단한 입력 중 알림
threadClient.sendTypingNotification();
스레드 작업
// 스레드 속성 가져오기
ChatThreadProperties properties = threadClient.getProperties();
System.out.println("주제: " + properties.getTopic());
System.out.println("생성일: " + properties.getCreatedOn());
// 주제 업데이트
threadClient.updateTopic("새로운 프로젝트 토론 주제");
// 스레드 삭제
chatClient.deleteChatThread(threadId);
스레드 목록 조회
// 사용자의 모든 채팅 스레드 나열
PagedIterable threads = chatClient.listChatThreads();
for (ChatThreadItem thread : threads) {
System.out.println("스레드 ID: " + thread.getId());
System.out.println("주제: " + thread.getTopic());
System.out.println("마지막 메시지: " + thread.getLastMessageReceivedOn());
}
페이지 분할
import com.azure.core.http.rest.PagedResponse;
// 메시지 페이지 분할
int maxPageSize = 10;
ListChatMessagesOptions listOptions = new ListChatMessagesOptions()
.setMaxPageSize(maxPageSize);
PagedIterable pagedMessages = threadClient.listMessages(listOptions);
pagedMessages.iterableByPage().forEach(page -> {
System.out.println("페이지 상태 코드: " + page.getStatusCode());
page.getElements().forEach(msg ->
System.out.println("메시지: " + msg.getContent().getMessage()));
});
오류 처리
import com.azure.core.exception.HttpResponseException;
try {
threadClient.sendMessage(messageOptions);
} catch (HttpResponseException e) {
switch (e.getResponse().getStatusCode()) {
case 401:
System.out.println("Unauthorized - 토큰을 확인하세요");
break;
case 403:
System.out.println("Forbidden - 사용자가 스레드에 없습니다");
break;
case 404:
System.out.println("스레드를 찾을 수 없음");
break;
default:
System.out.println("오류: " + e.getMessage());
}
}
메시지 유형
| 유형 | 설명 |
|---|---|
TEXT |
일반 채팅 메시지 |
HTML |
HTML 형식 메시지 |
TOPIC_UPDATED |
시스템 메시지 - 토픽 변경됨 |
PARTICIPANT_ADDED |
시스템 메시지 - 참가자 참여 |
PARTICIPANT_REMOVED |
시스템 메시지 - 참가자가 퇴장했습니다 |
환경 변수
AZURE_COMMUNICATION_ENDPOINT=https://.communication.azure.com
AZURE_COMMUNICATION_USER_TOKEN=
모범 사례
- 토큰 관리 - 사용자 토큰은 만료되므로
CommunicationTokenRefreshOptions를사용하여 갱신 로직을 구현하십시오. - 페이지 매김 - 대용량 스레드의 경우
maxPageSize와함께listMessages(options)를사용하십시오. - 공유 내역 - 참가자를 추가할 때
shareHistoryTime을설정하여 메시지 표시 범위를 제어하십시오 - 메시지 유형 - 사용자 메시지에서 시스템 메시지(
PARTICIPANT_ADDED등)를 필터링하세요 - 읽음 확인 - 사용자가 메시지를 실제로 확인했을 때만 읽음 확인을 보내십시오
트리거 문구
- "채팅 애플리케이션 Java", "실시간 메시징 Java"
- "채팅 스레드", "채팅 참가자", "채팅 메시지"
- "읽음 확인", "입력 중 알림"
- "Azure Communication Services 채팅"
---
name: azure-communication-chat-java
description: Build real-time chat applications with thread management, messaging, participants, and read receipts using the Azure Communication Services Chat Java SDK.
license: MIT
---
# Azure Communication Chat (Java)
Build real-time chat applications with thread management, messaging, participants, and read receipts.
## Installation
```xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-chat</artifactId>
<version>1.6.0</version>
</dependency>
```
## Client Creation
```java
import com.azure.communication.chat.ChatClient;
import com.azure.communication.chat.ChatClientBuilder;
import com.azure.communication.chat.ChatThreadClient;
import com.azure.communication.common.CommunicationTokenCredential;
// ChatClient requires a CommunicationTokenCredential (user access token)
String endpoint = "https://<resource>.communication.azure.com";
String userAccessToken = "<user-access-token>";
CommunicationTokenCredential credential = new CommunicationTokenCredential(userAccessToken);
ChatClient chatClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
// Async client
ChatAsyncClient chatAsyncClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildAsyncClient();
```
## Key Concepts
| Class | Purpose |
|-------|---------|
| `ChatClient` | Create/delete chat threads, get thread clients |
| `ChatThreadClient` | Operations within a thread (messages, participants, receipts) |
| `ChatParticipant` | User in a chat thread with display name |
| `ChatMessage` | Message content, type, sender info, timestamps |
| `ChatMessageReadReceipt` | Read receipt tracking per participant |
## Create Chat Thread
```java
import com.azure.communication.chat.models.*;
import com.azure.communication.common.CommunicationUserIdentifier;
import java.util.ArrayList;
import java.util.List;
// Define participants
List<ChatParticipant> participants = new ArrayList<>();
ChatParticipant participant1 = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier("<user-id-1>"))
.setDisplayName("Alice");
ChatParticipant participant2 = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier("<user-id-2>"))
.setDisplayName("Bob");
participants.add(participant1);
participants.add(participant2);
// Create thread
CreateChatThreadOptions options = new CreateChatThreadOptions("Project Discussion")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(options);
String threadId = result.getChatThread().getId();
// Get thread client for operations
ChatThreadClient threadClient = chatClient.getChatThreadClient(threadId);
```
## Send Messages
```java
// Send text message
SendChatMessageOptions messageOptions = new SendChatMessageOptions()
.setContent("Hello, team!")
.setSenderDisplayName("Alice")
.setType(ChatMessageType.TEXT);
SendChatMessageResult sendResult = threadClient.sendMessage(messageOptions);
String messageId = sendResult.getId();
// Send HTML message
SendChatMessageOptions htmlOptions = new SendChatMessageOptions()
.setContent("<strong>Important:</strong> Meeting at 3pm")
.setType(ChatMessageType.HTML);
threadClient.sendMessage(htmlOptions);
```
## Get Messages
```java
import com.azure.core.util.paging.PagedIterable;
// List all messages
PagedIterable<ChatMessage> messages = threadClient.listMessages();
for (ChatMessage message : messages) {
System.out.println("ID: " + message.getId());
System.out.println("Type: " + message.getType());
System.out.println("Content: " + message.getContent().getMessage());
System.out.println("Sender: " + message.getSenderDisplayName());
System.out.println("Created: " + message.getCreatedOn());
// Check if edited or deleted
if (message.getEditedOn() != null) {
System.out.println("Edited: " + message.getEditedOn());
}
if (message.getDeletedOn() != null) {
System.out.println("Deleted: " + message.getDeletedOn());
}
}
// Get specific message
ChatMessage message = threadClient.getMessage(messageId);
```
## Update and Delete Messages
```java
// Update message
UpdateChatMessageOptions updateOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
threadClient.updateMessage(messageId, updateOptions);
// Delete message
threadClient.deleteMessage(messageId);
```
## Manage Participants
```java
// List participants
PagedIterable<ChatParticipant> participants = threadClient.listParticipants();
for (ChatParticipant participant : participants) {
CommunicationUserIdentifier user =
(CommunicationUserIdentifier) participant.getCommunicationIdentifier();
System.out.println("User: " + user.getId());
System.out.println("Display Name: " + participant.getDisplayName());
}
// Add participants
List<ChatParticipant> newParticipants = new ArrayList<>();
newParticipants.add(new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier("<new-user-id>"))
.setDisplayName("Charlie")
.setShareHistoryTime(OffsetDateTime.now().minusDays(7))); // Share last 7 days
threadClient.addParticipants(newParticipants);
// Remove participant
CommunicationUserIdentifier userToRemove = new CommunicationUserIdentifier("<user-id>");
threadClient.removeParticipant(userToRemove);
```
## Read Receipts
```java
// Send read receipt
threadClient.sendReadReceipt(messageId);
// Get read receipts
PagedIterable<ChatMessageReadReceipt> receipts = threadClient.listReadReceipts();
for (ChatMessageReadReceipt receipt : receipts) {
System.out.println("Message ID: " + receipt.getChatMessageId());
System.out.println("Read by: " + receipt.getSenderCommunicationIdentifier());
System.out.println("Read at: " + receipt.getReadOn());
}
```
## Typing Notifications
```java
import com.azure.communication.chat.models.TypingNotificationOptions;
// Send typing notification
TypingNotificationOptions typingOptions = new TypingNotificationOptions()
.setSenderDisplayName("Alice");
threadClient.sendTypingNotificationWithResponse(typingOptions, Context.NONE);
// Simple typing notification
threadClient.sendTypingNotification();
```
## Thread Operations
```java
// Get thread properties
ChatThreadProperties properties = threadClient.getProperties();
System.out.println("Topic: " + properties.getTopic());
System.out.println("Created: " + properties.getCreatedOn());
// Update topic
threadClient.updateTopic("New Project Discussion Topic");
// Delete thread
chatClient.deleteChatThread(threadId);
```
## List Threads
```java
// List all chat threads for the user
PagedIterable<ChatThreadItem> threads = chatClient.listChatThreads();
for (ChatThreadItem thread : threads) {
System.out.println("Thread ID: " + thread.getId());
System.out.println("Topic: " + thread.getTopic());
System.out.println("Last message: " + thread.getLastMessageReceivedOn());
}
```
## Pagination
```java
import com.azure.core.http.rest.PagedResponse;
// Paginate through messages
int maxPageSize = 10;
ListChatMessagesOptions listOptions = new ListChatMessagesOptions()
.setMaxPageSize(maxPageSize);
PagedIterable<ChatMessage> pagedMessages = threadClient.listMessages(listOptions);
pagedMessages.iterableByPage().forEach(page -> {
System.out.println("Page status code: " + page.getStatusCode());
page.getElements().forEach(msg ->
System.out.println("Message: " + msg.getContent().getMessage()));
});
```
## Error Handling
```java
import com.azure.core.exception.HttpResponseException;
try {
threadClient.sendMessage(messageOptions);
} catch (HttpResponseException e) {
switch (e.getResponse().getStatusCode()) {
case 401:
System.out.println("Unauthorized - check token");
break;
case 403:
System.out.println("Forbidden - user not in thread");
break;
case 404:
System.out.println("Thread not found");
break;
default:
System.out.println("Error: " + e.getMessage());
}
}
```
## Message Types
| Type | Description |
|------|-------------|
| `TEXT` | Regular chat message |
| `HTML` | HTML-formatted message |
| `TOPIC_UPDATED` | System message - topic changed |
| `PARTICIPANT_ADDED` | System message - participant joined |
| `PARTICIPANT_REMOVED` | System message - participant left |
## Environment Variables
```bash
AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.com
AZURE_COMMUNICATION_USER_TOKEN=<user-access-token>
```
## Best Practices
1. **Token Management** - User tokens expire; implement refresh logic with `CommunicationTokenRefreshOptions`
2. **Pagination** - Use `listMessages(options)` with `maxPageSize` for large threads
3. **Share History** - Set `shareHistoryTime` when adding participants to control message visibility
4. **Message Types** - Filter system messages (`PARTICIPANT_ADDED`, etc.) from user messages
5. **Read Receipts** - Send receipts only when messages are actually viewed by user
## Trigger Phrases
- "chat application Java", "real-time messaging Java"
- "chat thread", "chat participants", "chat messages"
- "read receipts", "typing notifications"
- "Azure Communication Services chat"
모든 파일
0개 파일azure-communication-chat-java 설치
스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.
ZIP 다운로드저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-communication-chat-java # Copy SKILL.md to your .claude/skills/ directory
복사





집
