@vchatcloud/sdk v1.3.1
클래스
Channel
메시지를 보내거나, 받은 메시지의 이벤트를 처리할 수 있는 객체입니다.
Remarks
대부분의 채팅 기능은 Channel 객체를 사용해서 구현할 수 있습니다. VChatCloud.joinChannel()을 통해 채널 인스턴스를 생성할 수 있습니다.
Example
const vchatcloud = new VChatCloud({ serviceId: "your-service-id" });
const channel = vchatcloud.joinChannel({
roomId: "my-room",
nickName: "사용자1"
}, (error, history) => {
if (!error) {
console.log("채널 입장 성공!");
}
});2
3
4
5
6
7
8
9
확장
EventEmitter
속성
| 속성 | 유형 | 설명 |
|---|---|---|
users | Record<string, User> | 접속한 유저 목록입니다. Remarks 키는 clientKey, 값은 User 객체입니다. |
nickName | string | 사용자의 닉네임입니다. |
roomId | string | 채널 키 입니다. |
roomName | string | 채팅방의 이름입니다. |
clientKey | string | 사용자의 고유 키입니다. |
grade | string | 사용자의 등급입니다. Example "user", "admin", "manager" |
userInfo? | any | 사용자의 정보입니다. |
leave? | (callback?: () => unknown) => void | 접속 중인 채팅방에서 퇴장합니다. Remarks 퇴장하면 채널 연결이 종료되고, 다른 사용자에게 onNotifyLeaveUser 이벤트가 전달됩니다.Example channel.leave(() => { console.log("채팅방 퇴장 완료"); }); |
toggleRTCAudioControl? | (bool?: boolean) => Promise<MediaStreamTrack> | 자신의 오디오 입력을 토글합니다. Remarks - true: 오디오 켜기 - false: 오디오 끄기 - 미설정: 현재 상태의 반대로 토글Example // 오디오 토글 channel.toggleRTCAudioControl(); // 오디오 끄기 channel.toggleRTCAudioControl(false); |
toggleRTCVideoControl? | (bool?: boolean) => Promise<MediaStreamTrack> | 자신의 비디오 입력을 토글합니다. Remarks - true: 비디오 켜기 - false: 비디오 끄기 - 미설정: 현재 상태의 반대로 토글Example // 비디오 토글 channel.toggleRTCVideoControl(); // 비디오 켜기 channel.toggleRTCVideoControl(true); |
toggleRTCShareMedia? | (bool: boolean) => void | 자신의 화면 공유를 토글합니다. Remarks - true: 화면 공유 시작 - false: 화면 공유 중지Example // 화면 공유 시작 channel.toggleRTCShareMedia(true); // 화면 공유 중지 channel.toggleRTCShareMedia(false); |
메소드
onNotifyMessage()
onNotifyMessage(
event:ChannelMessageEvent):unknown
새로운 메시지를 받았을 때 호출되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelMessageEvent |
반환 형식:
unknown
Remarks
이 메서드를 오버라이드하여 메시지를 처리할 수 있습니다. 반환값은 무시되므로 event를 그대로 반환하면 됩니다.
Example
channel.onNotifyMessage = (event) => {
console.log(`${event.nickName}: ${event.message}`);
// UI에 메시지 표시
addMessageToUI(event);
return event;
};2
3
4
5
6
onNotifyNotice()
onNotifyNotice(
event:ChannelMessageEvent):unknown
새로운 공지사항을 받았을 때 호출되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelMessageEvent |
반환 형식:
unknown
Example
channel.onNotifyNotice = (event) => {
alert(`공지: ${event.message}`);
return event;
};2
3
4
onNotifyCustom()
onNotifyCustom(
event:ChannelMessageEvent):unknown
커스텀 이벤트를 수신할 때 호출되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelMessageEvent |
반환 형식:
unknown
Remarks
커스텀 이벤트를 통해 애플리케이션별 기능을 구현할 수 있습니다.
Example
channel.onNotifyCustom = (event) => {
const data = JSON.parse(event.message);
if (data.action === "gameStart") {
startGame(data.params);
}
return event;
};2
3
4
5
6
7
onNotifyJoinUser()
onNotifyJoinUser(
event:ChannelJoinEvent):unknown
채팅방에 유저가 새로 접속할 때 호출되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelJoinEvent |
반환 형식:
unknown
Remarks
이 핸들러는 내부적으로 users 객체를 자동으로 업데이트합니다.
Example
channel.onNotifyJoinUser = (event) => {
console.log(`${event.nickName}님이 입장했습니다. (${event.currentUserCount}명)`);
return event;
};2
3
4
onNotifyLeaveUser()
onNotifyLeaveUser(
event:ChannelUserEvent):unknown
채팅방에 접속해 있는 유저가 퇴장할 때 호출되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelUserEvent |
반환 형식:
unknown
Remarks
이 핸들러는 내부적으로 users 객체에서 해당 사용자를 자동으로 제거합니다.
Example
channel.onNotifyLeaveUser = (event) => {
console.log(`${event.nickName}님이 퇴장했습니다.`);
return event;
};2
3
4
onNotifyKickUser()
onNotifyKickUser(
event:ChannelUserEvent):unknown
유저가 입장 제한될 때 호출되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelUserEvent |
반환 형식:
unknown
Remarks
채널의 모든 사용자에게 브로드캐스트됩니다.
Example
channel.onNotifyKickUser = (event) => {
console.log(`${event.nickName}님이 강퇴되었습니다.`);
return event;
};2
3
4
onNotifyUnkickUser()
onNotifyUnkickUser(
event:ChannelUserEvent):unknown
유저의 입장 제한이 해제될 때 호출되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelUserEvent |
반환 형식:
unknown
Example
channel.onNotifyUnkickUser = (event) => {
console.log(`${event.nickName}님의 강퇴가 해제되었습니다.`);
return event;
};2
3
4
onNotifyMuteUser()
onNotifyMuteUser(
event:ChannelPersonalEvent):unknown
유저가 채팅 제한될 때 호출되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelPersonalEvent |
반환 형식:
unknown
Remarks
채널의 모든 사용자에게 브로드캐스트됩니다.
Example
channel.onNotifyMuteUser = (event) => {
console.log(`${event.nickName}님이 채팅 제한되었습니다.`);
return event;
};2
3
4
onNotifyUnmuteUser()
onNotifyUnmuteUser(
event:ChannelPersonalEvent):unknown
유저의 채팅 제한이 해제될 때 호출되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelPersonalEvent |
반환 형식:
unknown
Example
channel.onNotifyUnmuteUser = (event) => {
console.log(`${event.nickName}님의 채팅 제한이 해제되었습니다.`);
return event;
};2
3
4
onPersonalKickUser()
onPersonalKickUser(
event:ChannelPersonalEvent):unknown
입장 제한당한 유저에게만 전달되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelPersonalEvent |
반환 형식:
unknown
Remarks
해당 유저는 채팅방의 연결이 종료되고, 입장 제한이 해제되기 전까지 다시 입장할 수 없습니다.
Example
channel.onPersonalKickUser = (event) => {
alert("입장이 제한되었습니다.");
// 채널 연결 종료 처리
return event;
};2
3
4
5
onPersonalMuteUser()
onPersonalMuteUser(
event:ChannelPersonalEvent):unknown
채팅 제한당한 유저에게만 전달되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelPersonalEvent |
반환 형식:
unknown
Example
channel.onPersonalMuteUser = (event) => {
alert("채팅이 제한되었습니다.");
disableMessageInput();
return event;
};2
3
4
5
onPersonalUnmuteUser()
onPersonalUnmuteUser(
event:ChannelPersonalEvent):unknown
채팅 제한이 해제된 유저에게만 전달되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelPersonalEvent |
반환 형식:
unknown
Example
channel.onPersonalUnmuteUser = (event) => {
alert("채팅 제한이 해제되었습니다.");
enableMessageInput();
return event;
};2
3
4
5
onPersonalDuplicateUser()
onPersonalDuplicateUser(
event:ChannelDuplicateEvent):unknown
로그인할 때 clientKey가 중복될 경우 기존 사용자에게만 전달되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelDuplicateEvent |
반환 형식:
unknown
Remarks
동일한 clientKey로 다른 곳에서 로그인하면 기존 연결이 끊어집니다.
Example
channel.onPersonalDuplicateUser = (event) => {
alert("다른 곳에서 로그인하여 연결이 종료됩니다.");
return event;
};2
3
4
onPersonalInvite()
onPersonalInvite(
event: {roomId:string; }):unknown
서브 채팅방에 초대된 유저에게만 전달되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | { roomId: string; } |
event.roomId | string |
반환 형식:
unknown
Remarks
서브 채팅방 ID는 일반적으로 {channel key}-{Date.now()}_{invite user client key} 형식입니다.
Example
channel.onPersonalInvite = (event) => {
if (confirm(`새 채팅방에 초대되었습니다. 입장하시겠습니까?`)) {
vchatcloud.joinChannel({ roomId: event.roomId, nickName: "사용자1" });
}
return event;
};2
3
4
5
6
onPersonalWhisper()
onPersonalWhisper(
event:ChannelMessageEvent):unknown
귓속말을 받은 유저에게만 전달되는 이벤트 핸들러입니다.
매개변수
| 매개변수 | 유형 |
|---|---|
event | ChannelMessageEvent |
반환 형식:
unknown
Example
channel.onPersonalWhisper = (event) => {
console.log(`[귓속말] ${event.nickName}: ${event.message}`);
showWhisperNotification(event);
return event;
};2
3
4
5
onDisconnected()
onDisconnected():
void
채널 연결이 종료될 때 호출되는 이벤트 핸들러입니다.
반환 형식:
void
Remarks
네트워크 오류, 강제 종료, leave() 호출 등으로 인해 연결이 끊어질 때 호출됩니다.
Example
channel.onDisconnected = () => {
console.log("채널 연결이 종료되었습니다.");
// UI 정리, 재연결 시도 등
};2
3
4
sendMessage()
sendMessage(
data: {message:string;mimeType?:MimeType;messageType?:string; } |FormData|FileList,callback?: (e:VChatCloudError,m:null) =>void):Promise<void>
채팅방에 메시지를 전송합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
data | { message: string; mimeType?: MimeType; messageType?: string; } | FormData | FileList |
callback? | (e: VChatCloudError, m: null) => void |
반환 형식:
Promise<void>
Remarks
텍스트 메시지, 파일, FormData 등 다양한 형식을 지원합니다. 파일 업로드는 자동으로 처리됩니다.
Example
// 텍스트 메시지 전송
channel.sendMessage({ message: "안녕하세요!" });
// 파일 전송
const fileInput = document.querySelector('input[type="file"]');
channel.sendMessage(fileInput.files);
// 콜백 사용
channel.sendMessage(
{ message: "안녕하세요!" },
(error, result) => {
if (error) console.error("전송 실패:", error);
else console.log("전송 성공!");
}
);2
3
4
5
6
7
8
9
10
11
12
13
14
15
sendNotice()
sendNotice(
data: {message:string;mimeType?:MimeType; },callback?: (e:VChatCloudError,m:null) =>void):void
공지사항을 채팅방에 전송합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
data | { message: string; mimeType?: MimeType; } |
data.message | string |
data.mimeType? | MimeType |
callback? | (e: VChatCloudError, m: null) => void |
반환 형식:
void
Remarks
공지사항은 채팅방의 모든 사용자에게 전달되며, onNotifyNotice 이벤트로 수신됩니다.
Example
channel.sendNotice({ message: "점심시간입니다." }, (error) => {
if (!error) console.log("공지 전송 완료!");
});2
3
sendWhisper()
sendWhisper(
data: {message:string;receivedClientKey:string; },callback?: (error:VChatCloudError,message:null) =>void):void
채팅방에서 특정 유저에게 귓속말을 전송합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
data | { message: string; receivedClientKey: string; } |
data.message | string |
data.receivedClientKey? | string |
callback? | (error: VChatCloudError, message: null) => void |
반환 형식:
void
Remarks
receivedClientKey에 지정한 상대방에게만 귓속말이 전송됩니다. 상대방은 onPersonalWhisper 이벤트로 귓속말을 수신합니다.
Example
channel.sendWhisper({
message: "비밀 메시지입니다.",
receivedClientKey: "target-user-key"
});2
3
4
sendCustom()
sendCustom(
data: {message:string; },callback?: (e:VChatCloudError,m:null) =>void):void
커스텀 이벤트를 전송합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
data | { message: string; } |
data.message | string |
callback? | (e: VChatCloudError, m: null) => void |
반환 형식:
void
Remarks
커스텀 이벤트를 통해 애플리케이션별 기능을 구현할 수 있습니다. JSON 형식의 데이터를 문자열로 변환하여 보낸 뒤, onNotifyCustom에서 받은 데이터를 역직렬화하여 사용할 수 있습니다.
See
Example
// 게임 시작 이벤트 전송
channel.sendCustom({
message: JSON.stringify({
action: "gameStart",
params: { level: 1, mode: "easy" }
})
});
// 수신 측
channel.onNotifyCustom = (event) => {
const data = JSON.parse(event.message);
if (data.action === "gameStart") {
startGame(data.params);
}
return event;
};2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
getAllUserList()
getAllUserList(
callback?: (err:VChatCloudError,clientList:User[]) =>void):void
채널에 접속한 유저 목록을 조회합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
callback? | (err: VChatCloudError, clientList: User[]) => void |
반환 형식:
void
Remarks
조회된 유저 목록은 자동으로 users 객체에도 업데이트됩니다.
Example
channel.getAllUserList((error, users) => {
if (!error) {
console.log(`총 ${users.length}명 접속 중`);
users.forEach(user => {
console.log(`- ${user.nickName} (${user.grade})`);
});
}
});2
3
4
5
6
7
8
muteUser()
muteUser(
data: {clientKey:string; },callback?: (e:VChatCloudError,m:null) =>void):void
선택한 유저를 채팅 제한시킵니다.
매개변수
| 매개변수 | 유형 |
|---|---|
data | { clientKey: string; } |
data.clientKey | string |
callback? | (e: VChatCloudError, m: null) => void |
반환 형식:
void
Remarks
관리자 권한이 필요합니다. 제한된 유저는 메시지를 전송할 수 없습니다.
Example
channel.muteUser({ clientKey: "spam-user-key" }, (error) => {
if (!error) console.log("채팅 제한 완료");
});2
3
unmuteUser()
unmuteUser(
data: {clientKey:string; },callback?: (e:VChatCloudError,m:null) =>void):void
선택한 유저의 채팅 제한을 해제합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
data | { clientKey: string; } |
data.clientKey | string |
callback? | (e: VChatCloudError, m: null) => void |
반환 형식:
void
Remarks
관리자 권한이 필요합니다.
Example
channel.unmuteUser({ clientKey: "user-key" });kickUser()
kickUser(
data: {clientKey:string; },callback?: (e:VChatCloudError,m:null) =>void):void
선택한 유저를 입장 제한시킵니다.
매개변수
| 매개변수 | 유형 |
|---|---|
data | { clientKey: string; } |
data.clientKey | string |
callback? | (e: VChatCloudError, m: null) => void |
반환 형식:
void
Remarks
관리자 권한이 필요합니다. 강퇴된 유저는 채널 연결이 끊어지고, 제한이 해제되기 전까지 재입장할 수 없습니다.
Example
channel.kickUser({ clientKey: "violator-key" }, (error) => {
if (!error) console.log("강퇴 완료");
});2
3
unkickUser()
unkickUser(
data: {clientKey:string; },callback?: (e:VChatCloudError,m:null) =>void):void
선택한 유저의 입장 제한을 해제합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
data | { clientKey: string; } |
data.clientKey | string |
callback? | (e: VChatCloudError, m: null) => void |
반환 형식:
void
Remarks
관리자 권한이 필요합니다.
Example
channel.unkickUser({ clientKey: "user-key" });sendInvite()
sendInvite(
data: {roomId:string;clientKey:string; },callback?: (e:VChatCloudError,success:boolean) =>void):void
기존 채팅방에 접속해있는 유저를 새로운 채팅방(서브 채널)에 초대합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
data | { roomId: string; clientKey: string; } |
data.roomId | string |
data.clientKey? | string |
callback? | (e: VChatCloudError, success: boolean) => void |
반환 형식:
void
Remarks
초대된 유저는 onPersonalInvite 이벤트를 받습니다.
Example
channel.sendInvite({
roomId: "new-room-123",
clientKey: "user-to-invite"
}, (error, success) => {
if (success) console.log("초대 전송 완료");
});2
3
4
5
6
setRTCLocalMedia()?
optionalsetRTCLocalMedia(media:HTMLMediaElement):void
자신의 영상 소스를 Video 태그에 설정합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
media | HTMLMediaElement |
반환 형식:
void
Remarks
WebRTC 화상 채팅 기능 사용 시 필요합니다. 내부적으로 HTMLVideoElement.srcObject에 MediaStream을 설정합니다.
Example
const localVideo = document.querySelector('#local-video');
channel.setRTCLocalMedia(localVideo);2
setRTCRemoteMedia()?
optionalsetRTCRemoteMedia(media:HTMLMediaElement,clientKey:string):void
참가자의 영상 소스를 Video 태그에 설정합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
media | HTMLMediaElement |
clientKey | string |
반환 형식:
void
Remarks
WebRTC 화상 채팅 기능 사용 시 참가자별 비디오를 표시하기 위해 사용합니다.
Example
channel.onNotifyJoinUser = (event) => {
const remoteVideo = document.createElement('video');
remoteVideo.autoplay = true;
document.body.appendChild(remoteVideo);
channel.setRTCRemoteMedia(remoteVideo, event.clientKey);
return event;
};2
3
4
5
6
7
setRTCShareMedia()?
optionalsetRTCShareMedia(media:HTMLMediaElement):void
본인의 화면 공유를 위한 Video 태그를 설정합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
media | HTMLMediaElement |
반환 형식:
void
Remarks
화면 공유 기능 사용 시 필요합니다.
Example
const shareVideo = document.querySelector('#share-video');
channel.setRTCShareMedia(shareVideo);2
VChatCloud
채팅방 관리에 사용되는 메인 클래스입니다.
Remarks
VChatCloud는 채팅 서버와의 연결을 관리하고, 채널(채팅방)의 생성, 입장, 퇴장 등을 담당합니다. 이 클래스의 인스턴스를 생성한 후 joinChannel을 통해 채팅방에 입장할 수 있습니다.
Example
// VChatCloud 인스턴스 생성
const vchatcloud = new VChatCloud({
serviceId: "your-service-id"
});
// 채팅방 입장
const channel = vchatcloud.joinChannel({
roomId: "my-room",
nickName: "사용자1"
}, (error, history) => {
if (!error) {
console.log("입장 성공!");
console.log("과거 메시지:", history);
}
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
생성자
생성자
new VChatCloud(
param: {serviceId?:string; }):VChatCloud
VChatCloud 인스턴스를 생성합니다.
매개변수
| 매개변수 | 유형 | 설명 |
|---|---|---|
param | { serviceId?: string; } | - |
param.serviceId? | string | VChatCloud 서비스 ID입니다. |
반환 형식:
Remarks
인스턴스 생성 시 서비스 ID를 지정해야 합니다. WebRTC 옵션 및 연결 옵션을 추가로 설정할 수 있습니다.
Example
const vchatcloud = new VChatCloud({
serviceId: "your-service-id"
});2
3
속성
| 속성 | 유형 | 설명 |
|---|---|---|
channels | Record<string, Channel> | 접속한 채널들을 roomId별로 관리하는 객체입니다.Remarks 키는 roomId, 값은 Channel 인스턴스입니다.Example // 특정 채널에 접근 const myChannel = vchatcloud.channels["my-room"]; if (myChannel) { myChannel.sendMessage({ message: "안녕하세요!" }); } |
clientKey | string | 현재 사용자의 고유 키입니다. Remarks 사용자를 식별하기 위한 고유한 값입니다. joinChannel 호출 시 clientKey를 지정하지 않으면 이 값이 사용됩니다. 애플리케이션에서 사용자별로 고유한 값을 생성하여 사용해야 합니다.Example const vchatcloud = new VChatCloud({ serviceId: "your-service-id" }); // 사용자 ID를 clientKey로 설정 vchatcloud.clientKey = "user-12345"; |
메소드
disconnect()
disconnect(
callback?: (err:VChatCloudError,res:null) =>void):void
VChatCloud 서버와의 연결을 종료합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
callback? | (err: VChatCloudError, res: null) => void |
반환 형식:
void
Remarks
모든 채널 연결이 끊어지며, 자동 재연결이 비활성화됩니다. 재연결하려면 새로운 인스턴스를 생성해야 합니다.
Example
vchatcloud.disconnect((error, result) => {
if (!error) {
console.log("연결 종료 완료");
}
});2
3
4
5
joinChannel()
joinChannel(
params: {[key:string]:any;roomId:string;clientKey?:string;nickName:string; },callback?: (err:VChatCloudError,res:MessageHistory[]) =>void):Channel
채팅방에 입장합니다.
매개변수
| 매개변수 | 유형 | 설명 |
|---|---|---|
params | {[key: string]: any; roomId: string; clientKey?: string; nickName: string; } | - |
params.roomId | string | 입장할 채팅방의 고유 식별자입니다. |
params.clientKey? | string | 사용자의 고유 키입니다. Remarks 지정하지 않으면 VChatCloud.clientKey의 값이 사용됩니다. 동일한 clientKey로 중복 접속 시 기존 연결이 끊어집니다. |
params.nickName? | string | 사용자의 닉네임입니다. |
callback? | (err: VChatCloudError, res: MessageHistory[]) => void | - |
반환 형식:
Remarks
채팅방이 존재하지 않으면 오류가 발생합니다. openChannel로 먼저 채팅방을 생성해야 합니다. 입장 성공 시 과거 채팅 내역이 콜백으로 전달됩니다. 반환된 Channel 객체를 통해 메시지를 주고받을 수 있습니다.
Example
const channel = vchatcloud.joinChannel({
roomId: "my-room",
nickName: "사용자1",
clientKey: "user-12345",
grade: "user" // 선택사항
}, (error, history) => {
if (error) {
console.error("입장 실패:", error);
return;
}
console.log("입장 성공!");
console.log("과거 메시지:", history);
// 메시지 전송
channel.sendMessage({ message: "안녕하세요!" });
});
// 이벤트 핸들러 설정
channel.onNotifyMessage = (event) => {
console.log(`${event.nickName}: ${event.message}`);
return event;
};2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
openChannel()
openChannel(
params:string| {roomId?:string;clientKey?:string; },callback?: (err:VChatCloudError,res: {address:string;body:boolean;type:string; }) =>void):void
채팅방을 생성합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
params | string | { roomId?: string; clientKey?: string; } |
callback? | (err: VChatCloudError, res: { address: string; body: boolean; type: string; }) => void |
반환 형식:
void
Remarks
실제로 입장하지 않고 채팅방만 생성합니다. 입장하려면 joinChannel을 사용하세요.
Throws
INVALID_STATE_ERR - 서버에 연결되지 않은 상태
Throws
INVALID_ROOMID_ERR - roomId 형식이 올바르지 않음 (최소 4자 이상의 영숫자)
Example
vchatcloud.openChannel("my-room", (error, result) => {
if (!error) {
console.log("채팅방 생성 완료");
}
});
// 또는 객체 형식으로
vchatcloud.openChannel({
roomId: "my-room",
clientKey: "optional-key"
});2
3
4
5
6
7
8
9
10
11
closeChannel()
closeChannel(
params:string| {roomId:string; },callback?: (err:VChatCloudError,res: {address:string;body:any;type:string; }) =>void):void
채팅방을 삭제합니다.
매개변수
| 매개변수 | 유형 |
|---|---|
params | string | { roomId: string; } |
callback? | (err: VChatCloudError, res: { address: string; body: any; type: string; }) => void |
반환 형식:
void
Remarks
채팅방을 완전히 삭제하며, 모든 사용자의 연결이 끊어집니다. 채팅방을 생성한 사용자(owner)만 삭제할 수 있습니다.
Throws
INVALID_STATE_ERR - 서버에 연결되지 않은 상태
Throws
INVALID_ROOMID_ERR - roomId 형식이 올바르지 않음
Example
vchatcloud.closeChannel("my-room", (error, result) => {
if (!error) {
console.log("채팅방 삭제 완료");
}
});
// 또는 객체 형식으로
vchatcloud.closeChannel({ roomId: "my-room" });2
3
4
5
6
7
8
인터페이스
VChatCloudError
VChatCloud API에서 발생하는 오류 정보를 담는 인터페이스입니다.
See
Example
channel.sendMessage({ message: "안녕하세요" }, (error, response) => {
if (error) {
console.error(`오류 코드: ${error.code}`);
console.error(`오류 메시지: ${error.message}`);
}
});2
3
4
5
6
속성
| 속성 | 유형 | 설명 |
|---|---|---|
code | string | 오류를 식별하는 고유 코드입니다. Example "10001", "10108" |
message | string | 오류에 대한 설명 메시지입니다. Example "INVALID_PARAMETER", "CHANNEL_ALREADY_DISCONNECTED" |
MessageHistory
과거 채팅 내역 데이터입니다.
Remarks
최신 채팅 내역이 배열의 앞부분에 위치하므로 주의하세요. 채팅 내역이 기록이 내림차순(역순)으로 나타납니다.
Example
vchatcloud.joinChannel({
roomId: "my-room",
nickName: "사용자1"
}, (error, history) => {
if (!error && history) {
history.forEach((msg) => {
console.log(`[${msg.date}] ${msg.nickName}: ${msg.message}`);
});
}
});2
3
4
5
6
7
8
9
10
속성
| 속성 | 유형 | 설명 |
|---|---|---|
logType | string | 로그의 타입을 나타냅니다. Example "message", "notice", "custom" |
roomId | string | 채널(채팅방)의 고유 식별자입니다. |
clientKey | string | 메시지를 보낸 사용자의 고유 키입니다. |
nickName | string | 메시지를 보낸 사용자의 닉네임입니다. |
message | string | 메시지 내용입니다. |
messageType | string | 메시지의 타입입니다. Example "normal", "notice" |
grade | string | 메시지를 보낸 사용자의 등급입니다. Example "user", "admin", "manager" |
date | string | 메시지가 전송된 날짜 및 시간입니다. Remarks 형식: YYYYMMDDHHmmssExample "20250130143000" (2025년 1월 30일 14시 30분 00초) |
mimeType? | MimeType | 메시지의 MIME 타입입니다. |
userInfo? | any | 사용자 정의 정보입니다. Remarks 애플리케이션에서 필요한 추가 정보를 저장할 수 있습니다. |
User
채널에 접속한 사용자 정보입니다.
Example
channel.getAllUserList((error, users) => {
if (!error) {
users.forEach((user) => {
console.log(`${user.nickName} (${user.grade})`);
});
}
});2
3
4
5
6
7
속성
ChannelBaseEvent
채널 이벤트의 기본 정보를 담는 인터페이스입니다.
Remarks
대부분의 채널 이벤트는 이 인터페이스를 확장합니다.
에 의해 확장됨
속성
ChannelJoinEvent
사용자가 채널에 입장했을 때 발생하는 이벤트 정보입니다.
Example
channel.onNotifyJoinUser = (event) => {
console.log(`${event.nickName}님이 입장했습니다.`);
console.log(`현재 인원: ${event.currentUserCount}명`);
return event;
};2
3
4
5
확장
속성
ChannelMessageEvent
채널에서 메시지가 수신되었을 때 발생하는 이벤트 정보입니다.
Example
channel.onNotifyMessage = (event) => {
console.log(`[${event.messageDt}] ${event.nickName}: ${event.message}`);
return event;
};2
3
4
확장
에 의해 확장됨
속성
| 속성 | 유형 | 설명 |
|---|---|---|
roomId | string | 이벤트가 발생한 채널의 고유 식별자입니다. |
nickName | string | 이벤트와 관련된 사용자의 닉네임입니다. |
clientKey | string | 이벤트와 관련된 사용자의 고유 키입니다. |
grade | string | 이벤트와 관련된 사용자의 등급입니다. Example "user", "admin", "manager" |
userInfo? | any | 사용자 정의 정보입니다. |
mimeType? | MimeType | 메시지의 MIME 타입입니다. |
message | string | 메시지 내용입니다. |
messageDt | string | 메시지가 전송된 날짜 및 시간입니다. Example "2025-01-30 14:30:00" |
messageCount | number | 채널에서 전송된 메시지의 총 개수입니다. |
ChannelReceiveWhisperEvent
귓속말을 수신했을 때 발생하는 이벤트 정보입니다.
Example
channel.onPersonalWhisper = (event) => {
console.log(`${event.nickName}님의 귓속말: ${event.message}`);
return event;
};2
3
4
확장
속성
| 속성 | 유형 | 설명 |
|---|---|---|
roomId | string | 이벤트가 발생한 채널의 고유 식별자입니다. |
nickName | string | 이벤트와 관련된 사용자의 닉네임입니다. |
clientKey | string | 이벤트와 관련된 사용자의 고유 키입니다. |
grade | string | 이벤트와 관련된 사용자의 등급입니다. Example "user", "admin", "manager" |
userInfo? | any | 사용자 정의 정보입니다. |
mimeType? | MimeType | 메시지의 MIME 타입입니다. |
message | string | 메시지 내용입니다. |
messageDt | string | 메시지가 전송된 날짜 및 시간입니다. Example "2025-01-30 14:30:00" |
messageCount | number | 채널에서 전송된 메시지의 총 개수입니다. |
receivedClientKey | string | 귓속말을 받는 사용자의 고유 키입니다. |
ChannelSendWhisperEvent
귓속말을 전송했을 때 발생하는 이벤트 정보입니다.
확장
속성
| 속성 | 유형 | 설명 |
|---|---|---|
roomId | string | 이벤트가 발생한 채널의 고유 식별자입니다. |
nickName | string | 이벤트와 관련된 사용자의 닉네임입니다. |
clientKey | string | 이벤트와 관련된 사용자의 고유 키입니다. |
grade | string | 이벤트와 관련된 사용자의 등급입니다. Example "user", "admin", "manager" |
userInfo? | any | 사용자 정의 정보입니다. |
mimeType? | MimeType | 메시지의 MIME 타입입니다. |
message | string | 메시지 내용입니다. |
messageDt | string | 메시지가 전송된 날짜 및 시간입니다. Example "2025-01-30 14:30:00" |
messageCount | number | 채널에서 전송된 메시지의 총 개수입니다. |
receivedClientKey | string | 귓속말을 받는 사용자의 고유 키입니다. |
receivedNickName | string | 귓속말을 받는 사용자의 닉네임입니다. |
ChannelUserEvent
채널 내 사용자 상태 변경 이벤트 정보입니다.
Remarks
사용자 퇴장, 강퇴 등의 이벤트에서 사용됩니다.
Example
channel.onNotifyLeaveUser = (event) => {
console.log(`${event.nickName}님이 퇴장했습니다.`);
console.log(`남은 인원: ${event.currentUserCount}명`);
return event;
};2
3
4
5
속성
| 속성 | 유형 | 설명 |
|---|---|---|
clientKey | string | 이벤트와 관련된 사용자의 고유 키입니다. |
nickName | string | 이벤트와 관련된 사용자의 닉네임입니다. |
currentUserCount | number | 현재 채널에 접속 중인 사용자 수입니다. |
ChannelPersonalEvent
특정 사용자에게만 전달되는 개인 이벤트 정보입니다.
Remarks
채팅 제한, 강퇴 등 개인에게만 전달되는 이벤트에서 사용됩니다.
Example
channel.onPersonalMuteUser = (event) => {
console.log(`채팅이 제한되었습니다. (${event.messageDt})`);
return event;
};2
3
4
속성
| 속성 | 유형 | 설명 |
|---|---|---|
clientKey | string | 이벤트 대상 사용자의 고유 키입니다. |
nickName | string | 이벤트 대상 사용자의 닉네임입니다. |
messageDt | number | 이벤트 발생 시각입니다. (타임스탬프) Example 1706598600000 |
ChannelDuplicateEvent
중복 로그인이 감지되었을 때 발생하는 이벤트 정보입니다.
Remarks
동일한 clientKey로 다른 곳에서 로그인하면 기존 사용자에게 전달됩니다.
Example
channel.onPersonalDuplicateUser = (event) => {
alert("다른 곳에서 로그인하여 연결이 종료됩니다.");
return event;
};2
3
4
속성
| 속성 | 유형 | 설명 |
|---|---|---|
clientKey | string | 중복 로그인된 사용자의 고유 키입니다. |
messageDt | number | 이벤트 발생 시각입니다. (타임스탬프) Example 1706598600000 |
타입 별칭
MimeType
MimeType =
"text"|"emoji"|"emoji_img"|"file"
메시지의 콘텐츠 타입을 나타내는 타입입니다.
Example
// 텍스트 메시지 전송
channel.sendMessage({ message: "안녕하세요", mimeType: "text" });
// 파일 메시지 전송
channel.sendMessage({ message: fileData, mimeType: "file" });2
3
4
5