3 글 보임 - 1 에서 3 까지 (총 3 중에서)
-
글쓴이글
-
2022년 8월 19일 02:26 #43041
김노아참가자채팅을 작성하고 전송 버튼을 눌렀을 때, 채팅창에 작성한 채팅이 실시간 업데이트되지 않습니다. 1) 서버 코드에서 console.log(result.fullDocument) 했을 때 콘솔 창에 제가 방금 작성한 채팅이 출력됩니다. 2) DB에서도 저장이 됩니다. 3) 채팅방을 눌렀을 때는 방금 작성한 채팅까지 업데이트가 됩니다. 2) -chat.ejs 코드에서는 eventSource로 제가 방금 작성한 댓글을 받았다면 아래의 console.log(가져온거)으로 콘솔창에 출력되야 한다고 생각이 드는데 일단 이부분에서 출력이 되지 않습니다. -응답.write도 틀리지 않게 작성한 것 같은데 어디서 잘못되었는지 잘 모르겠습니다.
eventSource.addEventListener('test', function (e){ ........ let 가져온거 = JSON.parse(e.data) console.log(가져온거) ------------------------------------------------------------------------------------------------------------------------------------------ // server.js
app.get("/message/:id", checkLogIn, function (요청, 응답) { 응답.writeHead(200, { Connection: "keep-alive", "Content-Type": "text/event-stream", "Cache-Control": "no-cache", });
db.collection("message") .find({ parent: 요청.params.id }) .toArray() .then((result) => { 응답.write("event: test\n"); 응답.write(`data: ${JSON.stringify(result)}\n\n`); });
const pipeline = [{ $match: { "fullDocument.parent": 요청.params.id } }]; const collection = db.collection("message"); const changeStream = collection.watch(pipeline); changeStream.on("change", (result) => { console.log(result.fullDocument); 응답.write("event: test\n"); 응답.write("data :" + JSON.stringify([result.fullDocument]) + "\n\n"); }); }); ------------------------------------------------------------------------------------------------------------------------------------------- // chat.ejs
let 지금누른채팅방id let eventSource $('.list-group-item').click(function(){ 지금누른채팅방id = this.dataset.id;
$('.chat-content').html('') // 클릭할 때마다 실시간소통채널이 새로 생기는 것을 방지 if(eventSource != undefined){ eventSource.close() } eventSource = new EventSource(`/message/${지금누른채팅방id}`); eventSource.addEventListener('test', function (e){ let 가져온거 = JSON.parse(e.data) console.log(가져온거) 가져온거.forEach(element => { $('.chat-content').append(`<li><span class="chat-box">${element.content}</span></li>`) });
});
})
-
글쓴이글
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
- 답변은 로그인 후 가능합니다.