채팅기능을 구현하려면 항시 서버와 유저간은 실시간으로 데이터 전송이 이루어져야 한다.
그러기 위해서는 몇 가지의 기능들이 필수적으로 존재해야 하는데, 별도의 설명 없이 코딩만 기재하겠다.
1. 채팅기능 구현을 위한 Middleware
응답.writeHead(200,{ "Connection": "keep-alive", "Content-Type": "text/event-stream", "Cache-Control": "no-cache", });
2. 채팅 데이터전달을 위한 필수 메서드
res.write('event: test\n'); // 채팅 데이터전달을 위한 필수 메서드(1) res.write('data: '+JSON.stringify(출력결과변수)+'\n\n');
3. 채팅기능을 구현하기 위한 기능
eventSource = new EventSource('/message/'+채팅방의고유한아이디); // GET방식으로 넘김 eventSource.addEventListener('test', function(e){ console.log('e.data : '+e.data) console.log(JSON.parse(e.data)) );
app.get('/message/:id', 사용중인미들웨어(별도설명없음), function(req, res) {
// 채팅기능 구현을 위한 Middleware
응답.writeHead(200,{
"Connection": "keep-alive",
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
});
db.collection('DB이름은메세지').find({채팅방이름:req.params.id}).toArray().then((출력결과변수)=>{
res.write('event: test\n'); // 채팅 데이터전달을 위한 필수 메서드(1)
res.write('data : '+JSON.stringify(출력결과변수)+'\n\n'); // 채팅 데이터전달을 위한 필수 메서드(2)
});
});
var 채팅방의고유한아이디; // 다른 함수에서도 사용해야 하기에 전역변수로 지정함
$('.어디클래스').click(function(e){
채팅방의고유한아이디=this.dataset.id;
// 채팅기능을 구현하기 위한 기능
eventSource = new EventSource('/message/'+채팅방의고유한아이디); // GET방식으로 넘김
eventSource.addEventListener('test', function(e){
console.log('e.data : '+e.data)
console.log(JSON.parse(e.data))
);
});
채팅에서 나눈 대화들을 출력해야 하는데!
그 어떤 값도 출력되지 않는 에러가 발생했다.
res.write('data : '+JSON.stringify(출력결과변수)+'\n\n');
data와 :(쌍점이라고 부른다) 사이에는 띄어쓰기가 있으면 안된다..^^
res.write('data : '+JSON.stringify(출력결과변수)+'\n\n');
좋은 정보 감사합니다