Azure Communication Chat Java

作者 microsoft354361d83247MIT收录于 2026年10月8日更新于 2026年10月8日

Build real-time chat applications with Azure Communication Services Chat Java SDK. Use when implementing chat threads, messaging, participants, read receipts, typing notifications, or real-time chat features.

精选仅含说明Software Development
AI 生成的概览

指导 Java 开发者使用 Azure 通信服务聊天 SDK 构建实时聊天功能。

功能
提供使用 Azure 通信服务聊天 SDK 创建聊天线程、发送和管理消息、处理参与者、已读回执和正在输入通知的 Java 代码模式。内容涵盖客户端设置、分页、错误处理和消息类型,并附带参考示例文件。交付物是实施指导,而非可运行的应用。
适用场景
适用于在 Azure 通信服务上为 Java 应用实现实时聊天时,例如聊天线程、消息收发、参与者、已读回执或正在输入通知。适合需要具体 SDK 用法示例和最佳实践的开发者。
运行要求
需要 com.azure:azure-communication-chat Java 包、Azure 通信服务终结点以及用户访问令牌凭据。需要访问 Azure 通信服务的网络连接。不包含脚本,仅有说明文档和参考文档。

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 clientChatAsyncClient chatAsyncClient = new ChatClientBuilder()    .endpoint(endpoint)    .credential(credential)    .buildAsyncClient();

Key Concepts

ClassPurpose
ChatClientCreate/delete chat threads, get thread clients
ChatThreadClientOperations within a thread (messages, participants, receipts)
ChatParticipantUser in a chat thread with display name
ChatMessageMessage content, type, sender info, timestamps
ChatMessageReadReceiptRead 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 participantsList<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 threadCreateChatThreadOptions options = new CreateChatThreadOptions("Project Discussion")    .setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(options);String threadId = result.getChatThread().getId();
// Get thread client for operationsChatThreadClient threadClient = chatClient.getChatThreadClient(threadId);

Send Messages

java
// Send text messageSendChatMessageOptions messageOptions = new SendChatMessageOptions()    .setContent("Hello, team!")    .setSenderDisplayName("Alice")    .setType(ChatMessageType.TEXT);
SendChatMessageResult sendResult = threadClient.sendMessage(messageOptions);String messageId = sendResult.getId();
// Send HTML messageSendChatMessageOptions 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 messagesPagedIterable<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 messageChatMessage message = threadClient.getMessage(messageId);

Update and Delete Messages

java
// Update messageUpdateChatMessageOptions updateOptions = new UpdateChatMessageOptions()    .setContent("Updated message content");
threadClient.updateMessage(messageId, updateOptions);
// Delete messagethreadClient.deleteMessage(messageId);

Manage Participants

java
// List participantsPagedIterable<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 participantsList<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 participantCommunicationUserIdentifier userToRemove = new CommunicationUserIdentifier("<user-id>");threadClient.removeParticipant(userToRemove);

Read Receipts

java
// Send read receiptthreadClient.sendReadReceipt(messageId);
// Get read receiptsPagedIterable<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 notificationTypingNotificationOptions typingOptions = new TypingNotificationOptions()    .setSenderDisplayName("Alice");
threadClient.sendTypingNotificationWithResponse(typingOptions, Context.NONE);
// Simple typing notificationthreadClient.sendTypingNotification();

Thread Operations

java
// Get thread propertiesChatThreadProperties properties = threadClient.getProperties();System.out.println("Topic: " + properties.getTopic());System.out.println("Created: " + properties.getCreatedOn());
// Update topicthreadClient.updateTopic("New Project Discussion Topic");
// Delete threadchatClient.deleteChatThread(threadId);

List Threads

java
// List all chat threads for the userPagedIterable<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 messagesint 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

TypeDescription
TEXTRegular chat message
HTMLHTML-formatted message
TOPIC_UPDATEDSystem message - topic changed
PARTICIPANT_ADDEDSystem message - participant joined
PARTICIPANT_REMOVEDSystem message - participant left

Environment Variables

bash
AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.comAZURE_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"

来源与署名

来源:microsoft/skills位于.github/plugins/azure-sdk-java/skills/azure-communication-chat-java提交354361d

许可证: MIT

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架