node.js 채팅 구현
- 프로그래밍/nuxt.js,node.js
- 2021. 7. 14.
app.js
//채팅에 필요한 모듈s
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const fs = require('fs');
const io = require('socket.io')(server);
app.use(express.static('src'));
app.get('/', function (req, res) {
fs.readFil('./src/index.html', (err, data) => {
if (err) throw err;
res.writeHead(200, {
'Content-Type': 'text/html'
})
.write(data)
.end();
});
});
io.sockets.on('connection', function (socket) {
console.log('소켓연결완료');
socket.on('newUserConnect', function (name) {
console.log('채팅방 입장');
socket.name = name;
var message = name + '님이 접속했습니다';
io.sockets.emit('updateMessage', {
name: 'SERVER',
message: message
});
});
socket.on('disconnect', function () {
var message = socket.name + '님이 퇴장했습니다';
socket.broadcast.emit('updateMessage', {
name: 'SERVER',
message: message
});
})
socket.on('sendMessage', function (data) {
console.log("send message");
data.name = socket.name;
io.sockets.emit('updateMessage', data);
});
});
/**/
server.listen(8000, function () {
console.log('서버 실행중...');
});
index.js
'use strict';
var socket = io();
// 접속 되었을 때 실행
socket.on('connect', function () {
var name = prompt('대화명을 입력해주세요.', '');
socket.emit('newUserConnect', name);
});
var chatWindow = document.getElementById('chatWindow');
socket.on('updateMessage', function (data) {
if (data.name === 'SERVER') {
var infoEl = document.getElementById('info');
infoEl.innerHTML = data.message;
setTimeout(() => {
infoEl.innerText = '';
}, 3000);
} else {
var chatMessageEl = drawChatMessage(data);
chatWindow.appendChild(chatMessageEl);
chatWindow.scrollTop = chatWindow.scrollHeight;
}
});
function drawChatMessage(data) {
var wrap = document.createElement('P');
var message = document.createElement('span');
var name = document.createElement('span');
name.innerText = data.name;
message.innerText = data.message;
name.classList.add('output__user__name');
message.classList.add('output__user__message');
wrap.classList.add('output__user');
wrap.dataset.id = socket.id;
wrap.appendChild(name);
wrap.appendChild(message);
return wrap;
}
var sendButton = document.getElementById('chatMessageSendBtn');
var chatInput = document.getElementById('chatInput');
sendButton.addEventListener('click', sendChattingMessage);
chatInput.addEventListener('keydown', function (key) {
if (key.keyCode == 13) {
sendChattingMessage();
}
})
function sendChattingMessage() {
var message = chatInput.value;
if (!message) return false;
socket.emit('sendMessage', {
message
});
chatInput.value = '';
}/**/
index.css
@charset "utf-8"; .app__wrap{ margin: 0 auto; padding: 50px 0 0; position: relative; width: 100%; max-width: 350px; min-width: 200px; font-size: 14px; border-top: 20px solid #5c007a; box-sizing: border-box; box-shadow: 1px 1px 5px rgba(0,0,0,0.1); } .app__info{ position: absolute; top: 0; width: 100%; height: 50px; text-align: center; line-height: 50px; color: #fff; background: #8e24aa; } .app__window{ overflow-y: auto; padding: 10px 20px; height: 400px; background: #e1e2e1; } .output__user{ margin: 0; margin-bottom: 10px; } .output__user__name{ margin-right:10px; font-weight:700; } .app__input__wrap{ padding: 10px; background: #f5f5f6; } .app__input__wrap:after{ content:''; display:block; clear:both; } .app__input{ float: left; display: block; width: 80%; height: 25px; border: 1px solid #ccc; box-sizing: border-box; } .app__button{ float: left; display: block; width: 20%; height: 25px; border: 1px solid #ccc; border-left: 0; background: #fff; box-sizing: border-box; cursor: pointer; }
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="http://ptest.popomon.com:8000/css/index.css">
<title>chat-app</title>
</head>
<body>
<div class="app__wrap">
<div id="notice" class="app__info"></div>
<div id="chatWindow" class="app__window"></div>
<div class="app__input__wrap">
<input id="chatInput" type="text" class="app__input" placeholder="대화를 입력해주세요." autofocus>
<button id="chatMessageSendBtn" class="app__button">전송</button>
</div>
</div>
<script src="http://ptest.popomon.com:8000/socket.io/socket.io.js"></script>
<script src="http://ptest.popomon.com:8000/js/index.js"></script>
</body>
</html>
참고
https://codevkr.tistory.com/61?category=719250
★참고2
roomId
https://fred16157.github.io/node.js/nodejs-socketio-communication-room-and-namespace/
'프로그래밍 > nuxt.js,node.js' 카테고리의 다른 글
node.js javascsrip 클로저 (0) | 2021.07.15 |
---|---|
node.js javascript 스코프(유효 범위)와 호이스팅(끌어올림) (0) | 2021.07.15 |
node.js +express + forever (1) | 2021.07.12 |
node.js 설치 (0) | 2021.07.12 |
nuxt.js 시작 참고 사이트 (0) | 2021.05.27 |