채팅 메시지
채팅 메시지를 보내고 받기 위해서는 필요한 객체 선언과 채팅창 기능들이 준비되어야 합니다. 준비에 관한 세부 내용은 준비사항 문서를 참고합니다.
메시지 전송
채팅 메시지를 전송하는 방법입니다.
channel.sendMessage(
{
message: "전송될 메시지",
mimeType: "text",
},
function (err) {
// 성공 시에는 null, 오류 시 err 객체 리턴
// 예: {code: -1, type: "TIMEOUT", message: "Timed out after waiting 30000(ms) ..."}
if (err) openError("메시지 전송을 실패하였습니다.");
}
);
2
3
4
5
6
7
8
9
10
11
파라미터 값
값 식별자 설명 message String 전송할 메시지 mimeType String 메시지형태 (text: 일반텍스트, emoji: 이모지) 결과 값
값 식별자 설명 code String 에러 코드 message String 에러 메시지
프로젝트에 적용할 코드
입력창 엔터 js
js$("#content").keydown(function (e) { if (e.keyCode == 13) { e.preventDefault(); channel.sendMessage({ message: $(this).text(), mimeType: "text", }); $(this).text(""); } });
1
2
3
4
5
6
7
8
9
10클릭 버튼 js
js$("#sendCounter").click(function (e) { channel.sendMessage({ message: $("#content").text(), mimeType: "text", }); $("#content").text(""); });
1
2
3
4
5
6
7이모지 버튼 js
js$("div.bottom div.emoji a").click(function () { channel.sendMessage({ message: $(this).text(), mimeType: "emoji", }); });
1
2
3
4
5
6
신규 메시지 이벤트
신규 메시지 수신 시 이벤트 처리 방법입니다.
channel.onNotifyMessage = function (event) {
// {"nickName":"홍길동","roomId":"e7works","clientKey":"USER_CLIENT_KEY","message":"전송될 메시지","mimeType":"text","messageDt":"20200826160708","messageCount":4979,"grade":"user"}
console.log(event);
};
2
3
4
푸시 결과 값
값 식별자 설명 nickName String 메시지를 전송한 채팅방 입장 유저의 별명 roomId String 채팅방 생성 후 발급받은 Channel Key clientKey String 메시지를 전송한 접속 단말 설정 고유키 message String 전송된 메시지 mimeType String 메시지형태 (text: 일반텍스트, emoji: 이모지) messageDt String 전송 날짜 ( yyyyMMddHHmmss
형식)messageCount String 채팅방 메시지 전송 수 grade String 메시지를 전송한 유저의 등급 ( 사용자등급표
에서 확인 )
프로젝트에 적용할 코드
channel.onNotifyMessage = function (event) {
write(event);
};
2
3
귓속말 메시지 전송
특정 유저에게만 메시지를 전송하는 방법입니다.
channel.sendWhisper(
{
message: "전송될 메시지(귓속말)",
mimeType: "text",
receivedClientKey: "RECEIVED_CLIENT_KEY",
},
function (err, msg) {
if (err) {
// 성공시에는 null, 오류시 err 객체 리턴 ({"code":10107,"type":"RECIPIENT_FAILURE","message":"USER_NOT_EXISTED"})
return console.log(err);
}
// 성공시 객체 리턴 {"nickName":"nickname","roomId":"e7works","clientKey":"2a66d6a3","message":"메시지","receivedClientKey":"chatSample","mimeType":"text","messageDt":"20200831122540","messageCount":5852,"grade":"user","receivedNickName":"홍길동"}
console.log(msg);
}
);
2
3
4
5
6
7
8
9
10
11
12
13
14
15
파라미터 값
값 식별자 설명 message String 전송할 메시지 mimeType String 메시지 형태 (text: 일반텍스트, emoji: 이모지) receivedClientKey String 수신 유저의 접속 단말 설정 고유키 결과 값
err
값 식별자 설명 code String 에러 코드 message String 에러 메시지 msg
값 식별자 설명 roomId String 채팅방 생성 후 발급받은 Channel Key nickName String 채팅방 입장 유저의 별명 clientKey String 메시지를 전송한 접속 단말 설정 고유키 message String 전송한 메시지 mimeType String 메시지 형태 (text: 일반텍스트, emoji: 이모지) messageDt String 전송 날짜 ( yyyyMMddHHmmss
형식)messageCount String 채팅방 메시지 전송 수 receivedNickName String 메시지를 받는 유저의 별명 receivedClientKey String 메시지를 받는 접속 단말 설정 고유키 grade String 메시지를 전송한 유저의 등급 ( 사용자등급표
에서 확인 )
프로젝트에 적용할 코드
var popupLayer = $("div.popupLayer");
var whisperLayer = $("ul.popup_content li:nth-child(1)", $("div.popupLayer"));
popupLayer.close = function () {
$("#whisper input[type=text][name=message]", whisperLayer).val("");
$("#whisper", this).hide();
$(this).hide();
};
$("button", whisperLayer).click(function (e) {
channel.sendWhisper(
{
message: $("input[type=text][name=message]", whisperLayer).val(),
receivedClientKey: popupLayer.data()["clientKey"],
},
function (err, msg) {
if (err) return openError(err.message);
write(msg, "whisperto");
}
);
e.preventDefault();
popupLayer.close();
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
개인 귓속말 메시지 이벤트
귓속말 메시지를 수신할 때 처리하는 방법입니다.
channel.onPersonalWhisper = function (event) {
// {"nickName":"홍길동","roomId":"e7works","clientKey":"CLIENT_KEY","message":"전송될 메시지(귓속말)","RECEIVED_CLIENT_KEY":"user고유키","mimeType":"text","messageDt":"20200826160933","messageCount":4981,"grade":"user"}
console.log("onPersonalWhisper", event);
};
2
3
4
푸시 결과 값
값 식별자 설명 roomId String 채팅방 생성 후 발급받은 Channel Key nickName String 채팅방 입장 유저의 별명 clientKey String 메시지를 전송한 접속 단말 설정 고유키 message Date 전송한 메시지 mimeType String 메시지 형태 (text: 일반텍스트, emoji: 이모지) messageDt String 전송 날짜 ( yyyyMMddHHmmss
형식)messageCount String 채팅방 메시지 전송 수 receivedClientKey String 메시지를 받는 접속 단말 설정 고유키 grade String 메시지를 전송한 유저의 등급 ( 사용자등급표
에서 확인 )
프로젝트에 적용할 코드
channel.onPersonalWhisper = function (event) {
write(event, "whisper");
};
2
3
파일 메시지
채팅에 파일을 전송하는 방법입니다.
채팅에 파일을 전송하려면 파일 공유 라이브러리를 사용하는 것이 가장 쉽습니다.
추가 라이브러리 사용이 어렵거나 직접 구현해야 한다면, 아래와 같이 파일을 API로 업로드한 뒤 채팅 메시지로 정보를 전송할 수 있습니다.
파일은 최대 100MB이하의 파일까지 업로드 가능하며, 7일간 유지됩니다. 만료기간이 지난 이후에는 자동으로 서버에서 삭제되며 다운로드 할 수 없습니다. 해당 채팅방에 접근 가능한 모든 사용자가 파일을 볼 수 있으므로, 개인정보가 포함된 파일, 실행 파일 등은 업로드하지 마십시오.
파일 업로드
// 반드시 async 함수 내에서 실행하세요!
async function uploadFile() {
const input = document.querySelector("input#file"); // 실제 파일 input 셀렉터로 변경
if (!input.files.length) {
alert("파일을 선택해주세요.");
return;
}
const file = input.files[0];
const roomId = "YOUR_ROOM_ID";
const formData = new FormData();
formData.append("file", file);
formData.append("roomId", roomId);
const res = await fetch("https://www.vchatcloud.com/api/openapi/saveFile", {
method: "POST",
body: formData,
});
const json = await res.json();
if (json.result_cd !== 1) {
alert("파일 업로드 실패: " + json.result_msg);
return;
}
// 파일 전송 성공 시 메시지 전송
sendFileMessage(json.data);
}
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
파일 업로드 응답 구조
필드 | 타입 | 설명 |
---|---|---|
fileKey | String | 업로드된 파일 ID |
fileNm | String | 파일의 원본 이름 |
fileExt | String | 파일 확장자 |
fileSize | Number | 파일 크기 (byte) |
expire | String | 만료 일자 (yyyy-MM-dd) |
채팅 메시지로 파일 정보 전송
function sendFileMessage(fileData) {
channel.sendMessage({
message: JSON.stringify([
{
id: fileData.fileKey,
name: fileData.fileNm,
type: fileData.fileExt,
size: fileData.fileSize,
expire: fileData.expire,
},
]),
mimeType: "file",
});
}
2
3
4
5
6
7
8
9
10
11
12
13
14
파일 수신 이벤트
채팅방에서는 신규 메시지 이벤트에서 mimeType
이 file
인 경우 파일 메시지임을 알 수 있습니다.
channel.onNotifyMessage = function (event) {
if (event.mimeType === "file") {
fileWrite(event);
return;
}
// ... 기존 메시지 처리
};
2
3
4
5
6
7
파일 메시지 표시 예시
function fileWrite(msg, pre, isPrivate) {
const data = JSON.parse(msg.message)[0];
if (!data) return;
// 예시: 파일 다운로드 링크 생성
const fileUrl = `https://www.vchatcloud.com/api/openapi/loadFile?fileKey=${data.id}`;
const html = `
<div class="content">
<strong>${data.name}</strong>
<span>(${(data.size / 1024).toFixed(1)} KB, ~${data.expire})</span>
<a href="${fileUrl}" download>다운로드</a>
</div>
`;
// 채팅 영역에 추가
$("#content1").append(html);
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
이모티콘 메시지
이모티콘 전송
이모티콘 전송 시에는 일반 메시지를 보낼 때와 비슷하며, mimeType
을 emoji_img
로 설정하고, message
속성에 이미지 주소를 전송합니다.
TIP
만약 이모티콘을 변경하시려면, img/emoticon
경로의 이미지 파일을 변경하시거나, js/emoji.js
의 customEmojiInit
함수를 수정하여 원하는 이모티콘을 사용하도록 설정할 수 있습니다.
channel.sendMessage({
// ...기존 코드
mimeType: "emoji_img",
message: "img/emoticon/emo01/emo01_001.png",
})
2
3
4
5
이모티콘 수신
채팅방에서는 신규 메시지 이벤트에서 mimeType
이 emoji_img
인 경우 이모티콘 메시지임을 알 수 있습니다.
channel.onNotifyMessage = function (event) {
const container = $("#content1");
if (event.mimeType === "emoji_img") {
const emoticon = `
<span class="comment">
<img src="${event.message}" alt="emoticon" />
</span>`;
container.append(emoticon);
return;
}
// ... 기존 메시지 처리
};
2
3
4
5
6
7
8
9
10
11
12
전체 코드
메시지 이벤트 전체코드
$(function () {
// 입력창 엔터
$("div.bottom div.emoji a").click(function () {
channel.sendMessage({
message: $(this).text(),
mimeType: "emoji",
});
});
// 클릭 버튼
$("#sendCounter").click(function (e) {
channel.sendMessage({
message: $("#content").text(),
mimeType: "text",
});
$("#content").text("");
});
// 이모지 버튼
$("#content").keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
channel.sendMessage({
message: $(this).text(),
mimeType: "text",
});
$(this).text("");
}
});
// 특정 유저로 메시지 전송
var popupLayer = $("div.popupLayer");
var whisperLayer = $("ul.popup_content li:nth-child(1)", $("div.popupLayer"));
popupLayer.close = function () {
$("#whisper input[type=text][name=message]", whisperLayer).val("");
$("#whisper", this).hide();
$(this).hide();
};
$("button", whisperLayer).click(function (e) {
channel.sendWhisper(
{
message: $("input[type=text][name=message]", whisperLayer).val(),
receivedClientKey: popupLayer.data()["clientKey"],
},
function (err, msg) {
if (err) return openError(err.message);
write(msg, "whisperto");
}
);
e.preventDefault();
popupLayer.close();
});
});
// chatInit() 부분은 login.js에 joinRoom 이 성공한 이후에 실행하도록 한다
function chatInit() {
// 신규 메시지 이벤트
channel.onNotifyMessage = function (event) {
write(event);
};
// 개인 귓속말 메시지 이벤트
channel.onPersonalWhisper = function (event) {
write(event, "whisper");
};
}
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