티스토리 뷰
0. 채팅 데이터 전송 시 파라미터에 id담기
<server.js>
app.post('/message/:id', 로그인했니, function (요청, 응답) { // <--
var 저장할거 = {
parent: 요청.body.parent,
content: 요청.body.content,
@@ -282,6 +284,25 @@ app.post('/message', 로그인했니, function (요청, 응답) {
});
});
1. 실시간 소통채널 열기
<server.js>
app.get('/message/:id', 로그인했니, function (요청, 응답) {
응답.writeHead(200, {
'Connection': 'keep-alive',
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
});
db.collection('message')
.find({ parent: 요청.params.id })
.toArray()
.then((결과) => {
응답.write('event: test\n'); // 사용자에게 데이터 전송 - event: 보낼데이터이름\n
// 응답.write('data:' + 결과 + '\n\n'); // 사용자에게 데이터 전송 - data: 보낼데이터\n\n
// -> 이렇게 보내면 toArray()때문에 깨짐. 서버에서 실시간 전송시 문자자료만 전송 가능
응답.write('data: ' + JSON.stringify(결과) + '\n\n'); // JSON으로 보내기
});
});
2. 채팅방 클릭시 만들어둔 채널로 입장
<chat.ejs>
var 지금누른채팅방id;
var eventsource;
// 채팅방 하나 클릭하면
$('.list-group-item').click(function () {
지금누른채팅방id = this.dataset.id;
// 여기 채널로 입장
eventsource = new EventSource('/message/' + 지금누른채팅방id);
eventsource.addEventListener('test', function (e) {
e.data; // 서버에서 보낸 데이터
console.log(JSON.parse(e.data));
});
});
$('#send').click(function () {
var 채팅내용 = $('#chat-input').val();
var 보낼거 = {
parent: 지금누른채팅방id,
content: 채팅내용,
};
$.post('/message', 보낼거).then(() => {
console.log('전송 성공');
});
});'Server > Node.js' 카테고리의 다른 글
| [Node.js] 채팅 - 5. WebSocket으로 실시간 업데이트 (0) | 2023.07.27 |
|---|---|
| [Node.js] 채팅 - 4. DB 변동사항 실시간 업데이트 (0) | 2023.07.27 |
| [Node.js] 채팅 - 2. 메세지 발행 (0) | 2023.07.26 |
| [Node.js] 채팅 - 1. 채팅방 (0) | 2023.07.25 |
| [Node.js] 이미지 업로드, 이미지 서버 만들기 (0) | 2023.07.20 |
댓글
