Are you an LLM? You can read better optimized documentation at /doc/javascript/chatting/sdk-overview.md for this page in Markdown format
JavaScript SDK 개요
VChatCloud JavaScript SDK는 웹 브라우저에서 실시간 채팅 기능을 구현할 수 있는 공식 라이브러리입니다.
이 문서에서 배울 내용
이 문서를 통해 다음과 같은 내용을 학습할 수 있습니다:
- SDK 설치 및 초기 설정 방법
- 채팅방 생성 및 참여 방법
- 실시간 메시지 송수신 구현
- 사용자 입장/퇴장 이벤트 처리
- 다양한 채팅 기능 활용법
사전 준비사항
시작하기 전에 다음 사항을 준비해주세요.
- 채널키(Channel Key): VChatCloud CMS에서 발급받은 채팅방 고유 식별자
- 서비스ID(Service ID): VChatCloud 계정의 이메일 주소
- 기본 JavaScript 지식: ES6+ 문법에 대한 이해
채널키 발급 방법은 Quick Start 가이드를 참고하세요.
시작하기
1. SDK 설치
VChatCloud SDK
프로젝트에 SDK를 설치하는 방법은 두 가지입니다.
방법 1: 패키지 매니저 사용
bash
# npm 사용
npm install @vchatcloud/sdk
# yarn 사용
yarn add @vchatcloud/sdk
# pnpm 사용
pnpm add @vchatcloud/sdk1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
방법 2: CDN 스크립트 태그 사용
html
<head>
<script src="https://www.vchatcloud.com/lib/vchatcloud-last.min.js"></script>
</head>1
2
3
2
3
2. 기본 사용법
2-1. SDK 초기화
먼저 VChatCloud 인스턴스를 생성합니다.
javascript
import { VChatCloud } from "@vchatcloud/sdk";
// VChatCloud 인스턴스 생성
const vChatCloud = new VChatCloud({
serviceId: "YOUR_SERVICE_ID"
});1
2
3
4
5
6
2
3
4
5
6
2-2. 채팅방 참여
joinChannel 메소드를 사용하여 채팅방에 참여합니다.
javascript
function joinChatRoom() {
try {
const channel = vChatCloud.joinChannel(
{
roomId: "YOUR_CHANNEL_KEY", // 채널키
clientKey: "user123", // 사용자 고유 ID
nickName: "홍길동" // 닉네임
},
(error, history) => {
if (error) {
console.error("참여 실패:", error);
return;
}
// 이전 대화 내역 처리
console.log("참여 성공");
history.forEach(msg => {
console.log(`${msg.nickName}: ${msg.message}`);
});
}
);
return channel;
} catch (error) {
console.error("오류 발생:", error);
}
}
// 채팅방 참여 실행
const myChannel = joinChatRoom();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
대화 내역 처리
콜백 함수의 history 매개변수는 이전 대화 내역을 포함합니다. 시간순으로 정렬되어 있으므로 일반적인 채팅 UI에서는 역순으로 정렬하여 사용하세요.
javascript
// 최신 메시지가 아래로 오도록 역순 정렬
history.reverse().forEach(msg => {
displayMessage(msg);
});1
2
3
4
2
3
4
2-3. 이벤트 핸들러 등록
채팅방에서 발생하는 이벤트를 처리하기 위해 이벤트 핸들러를 등록합니다.
javascript
if (myChannel) {
// 새 메시지 수신
myChannel.onNotifyMessage = (event) => {
console.log(`${event.nickName}: ${event.message}`);
displayMessage(event);
};
// 사용자 입장
myChannel.onNotifyJoinUser = (event) => {
console.log(`${event.nickName}님이 입장했습니다.`);
showJoinNotification(event.nickName);
};
// 사용자 퇴장
myChannel.onNotifyLeaveUser = (event) => {
console.log(`${event.nickName}님이 퇴장했습니다.`);
showLeaveNotification(event.nickName);
};
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2-4. 메시지 전송
sendMessage 메소드를 사용하여 메시지를 전송합니다.
javascript
// 기본 메시지 전송
myChannel.sendMessage({
message: "안녕하세요!"
});
// 입력창과 연동한 메시지 전송 예제
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
sendButton.addEventListener('click', () => {
const message = messageInput.value.trim();
if (message) {
myChannel.sendMessage({ message });
messageInput.value = '';
}
});1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
완전한 예제
다음은 기본적인 채팅 애플리케이션의 완전한 예제입니다:
javascript
import { VChatCloud } from "@vchatcloud/sdk";
class SimpleChatApp {
constructor() {
this.vChatCloud = new VChatCloud({
serviceId: "YOUR_SERVICE_ID"
});
this.channel = null;
}
init() {
try {
this.channel = this.vChatCloud.joinChannel(
{
roomId: "YOUR_CHANNEL_KEY",
clientKey: "user123",
nickName: "홍길동"
},
(error, history) => {
if (error) {
console.error("참여 실패:", error);
return;
}
// 이전 대화 내역 표시
history.reverse().forEach(msg => {
this.displayMessage(msg);
});
}
);
this.setupEventHandlers();
this.setupUI();
} catch (error) {
console.error("초기화 실패:", error);
}
}
setupEventHandlers() {
// 새 메시지 수신
this.channel.onNotifyMessage = (event) => {
this.displayMessage(event);
};
// 사용자 입장/퇴장
this.channel.onNotifyJoinUser = (event) => {
this.showNotification(`${event.nickName}님이 입장했습니다.`);
};
this.channel.onNotifyLeaveUser = (event) => {
this.showNotification(`${event.nickName}님이 퇴장했습니다.`);
};
}
setupUI() {
const sendButton = document.getElementById('sendButton');
const messageInput = document.getElementById('messageInput');
sendButton.addEventListener('click', () => {
this.sendMessage();
});
messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.sendMessage();
}
});
}
sendMessage() {
const messageInput = document.getElementById('messageInput');
const message = messageInput.value.trim();
if (message && this.channel) {
this.channel.sendMessage({ message });
messageInput.value = '';
}
}
displayMessage(event) {
const chatContainer = document.getElementById('chatContainer');
const messageElement = document.createElement('div');
messageElement.innerHTML = `
<strong>${event.nickName}:</strong> ${event.message}
`;
chatContainer.appendChild(messageElement);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
showNotification(text) {
const chatContainer = document.getElementById('chatContainer');
const notificationElement = document.createElement('div');
notificationElement.className = 'notification';
notificationElement.textContent = text;
chatContainer.appendChild(notificationElement);
}
}
// 애플리케이션 시작
const app = new SimpleChatApp();
app.init();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
API 레퍼런스
SDK에서 제공하는 주요 메소드와 이벤트 핸들러는 다음과 같습니다.
메시지 관련
| 메소드/이벤트 핸들러 | 설명 |
|---|---|
sendMessage() | 채팅방에 공개 메시지를 전송합니다. |
sendWhisper() | 특정 사용자에게 귓속말을 보냅니다. |
onNotifyMessage | 새로운 공개 메시지가 수신될 때 발생합니다. |
onPersonalWhisper | 자신에게 온 귓속말 메시지를 수신할 때 발생합니다. |
onNotifyNotice | 관리자가 보낸 공지사항 메시지를 수신할 때 발생합니다. |
onNotifyCustom | 사용자가 정의한 커스텀 메시지를 수신할 때 발생합니다. |
사용자 상태 관련
| 이벤트 핸들러 | 설명 |
|---|---|
onNotifyJoinUser | 새로운 사용자가 채팅방에 입장할 때 발생합니다. |
onNotifyLeaveUser | 사용자가 채팅방에서 퇴장할 때 발생합니다. |
onPersonalDuplicateUser | 동일한 계정(=clientKey)으로 다른 기기에서 중복 로그인 시 발생합니다. |
관리(운영) 기능 관련
| 이벤트 핸들러 | 설명 |
|---|---|
onNotifyKickUser | 특정 사용자가 채팅방에서 추방될 때 발생합니다. |
onNotifyUnkickUser | 추방된 사용자의 추방이 해제될 때 발생합니다. |
onNotifyMuteUser | 특정 사용자가 메시지 작성이 금지(침묵)될 때 발생합니다. |
onNotifyUnmuteUser | 침묵 처리된 사용자의 금지가 해제될 때 발생합니다. |
onPersonalMuteUser | 자신이 메시지 작성이 금지될 때 발생합니다. |
onPersonalUnmuteUser | 자신의 메시지 작성 금지가 해제될 때 발생합니다. |