Skip to content
Open

Cto #14

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
client-server/node_modules
test.js
4 changes: 4 additions & 0 deletions chat-server-nodejs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
222 changes: 222 additions & 0 deletions chat-server-nodejs/chat.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>

<script src="/socket.io/socket.io.js"></script>
<script>
document.addEventListener("DOMContentLoaded", () => {

const socket = io({ path: "/socket.io" });

const form = document.getElementById("form");
const input = document.getElementById("input");
const messages = document.getElementById("messages");
const chatHistoryButton = document.getElementById("chatHistoryAll")
const chatSearchedHistoryForm = document.getElementById("chatSearchedHistoryAll")

// connect to socket.server
socket.on("connect", (socket) => {
console.log("Connected to server");
});

// receive a broadcasting message from socket server
socket.on("msg", (chat) => {

console.log(chat);

const item = document.createElement("li");
item.textContent = chat;
messages.appendChild(item);
//window.scrollTo(0, document.body.scrollHeight) //최하단으로 스크롤;
});

// receive a chat from socket server
socket.on("chat", (chat) => {

console.log(chat);

const item = document.createElement("li");
item.textContent = `😒${chat.nickname} : ${chat.chatMsg} (보낸시간 : ${chat.time}, ${chat['socket.id']})`;
messages.appendChild(item);
//window.scrollTo(0, document.body.scrollHeight); //최하단으로 스크롤
});

// send a chat to socket server
form.addEventListener("submit", (e) => {
e.preventDefault();
if (input.value) {
socket.emit("msg", input.value);
input.value = "";
}
});

// change your nickname
const nickname_form = document.getElementById("nickname");
const nickname_input = document.getElementById("nickname_input");

nickname_form.addEventListener("submit", (e) => {
e.preventDefault();
if (nickname_input) {
socket.emit("nickname", nickname_input.value);
}
});

// show participating chat person number
const room_personnel = document.getElementById("room_personnel");
socket.on("room_info", (roomInfo)=>{
console.log("roomInfo.size", roomInfo.size);
console.log("roomInfo.rooms", roomInfo.rooms);
room_personnel.append(`(${roomInfo.size})`);

roomInfo.rooms.forEach((user)=>{
var room_person = document.createElement("li");
var textNode = document.createTextNode(user[0]);
room_person.append(textNode);
room_personnel.appendChild(room_person);
})
})


// bring chat history
chatHistoryButton.addEventListener('click', async function() {

try {
// 서버에 요청을 보내 채팅 기록을 가져옴
const response = await fetch('/api/chatSearch');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

const text = await response.text(); // Read response as text
const chatHistory = text ? JSON.parse(text) : []; // Parse JSON if not empty

// 채팅 기록을 콘솔에 출력
console.log("Chat History:", chatHistory);

// 채팅 기록을 페이지에 표시
const chatDisplay = document.getElementById('chatDisplay');
let chatHistoryHTML = '';
chatHistory.forEach( (chat) => {
chatHistoryHTML += `${chat.nickname} : ${chat.chatMsg} (${chat.time}) <br/>`;
})
chatDisplay.innerHTML = chatHistoryHTML;

window.scrollTo(0, document.body.scrollHeight); //최하단으로 스크롤
} catch (error) {
console.error("Error fetching chat history:", error);
}
});

// bring searched chat history
chatSearchedHistoryForm.addEventListener('submit', async function(e) {

e.preventDefault();

const searchTerm = document.getElementById('search-term').value;
const searchCondition = document.getElementById('search-Condition').value;

const url = new URL('/api/chatSearch', window.location.origin);
url.searchParams.append('searchTerm', searchTerm);
url.searchParams.append('searchCondition', searchCondition);

try {
// 서버에 요청을 보내 채팅 기록을 가져옴

const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

const text = await response.text(); // Read response as text
const chatSearchedHistory = text ? JSON.parse(text) : []; // Parse JSON if not empty

// 채팅 기록을 콘솔에 출력
console.log("Chat searched History:", chatSearchedHistory);

// 채팅 기록을 페이지에 표시
const chatDisplay = document.getElementById('chatDisplay');
let chatHistoryHTML = '';

chatSearchedHistory.forEach( (chat) => {
chatHistoryHTML += `${chat.nickname} : ${chat.chatMsg} (${chat.time}) <br/>`;
})
chatDisplay.innerHTML = chatHistoryHTML;

window.scrollTo(0, document.body.scrollHeight); //최하단으로 스크롤
} catch (error) {
console.error("Error fetching searched chat history:", error);
}
});
})

</script>

</head>
<body>
<!-- <h3>chat-server-nodejs에서 뿌리는 chat.html 에옹 (프론트)</h3> -->
<h1>쿠버맵티스 채팅방이에용</h1>
<br />

<ul id="room_personnel">채팅 참여 인원 </ul>

<br />

<ul id="messages">채팅 내용</ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>

<form id="nickname" action="">
<input id="nickname_input" autocomplete="off" /><button>
닉네임 변경
</button>
</form>

<br /><br /><br />
-----------------------------
<h3>개발 history</h3>
24.5.17(금) - 1:1 채팅기능 구현 (완료) <br/>
24.5.18(토) - 닉네임 변경기능 (완료) <br/>
24.5.18(토) - 채팅방 인원 수 표시, 최초 채팅방 접속일자 표시 (완료) <br/>
24.5.19(일) - 채팅방 접속자 표시, 채팅별 전송일자 표시 (완료) <br/>
24.5.20(월) - 채팅내용 몽고DB 저장하고 전체 채팅 조회하기 (완료) <br/>
24.5.22(수) - 특정 닉네임/날짜/채팅내용별로 채팅메세지 선택 조회하기 (완료)<br/>
<br/>
24.5.23(목) - (개념, 코드 정리해야되는데) <br/>
24.5.23(목) - 채팅방 따로 파기 (예정) <br/>
----------------------------- <br/><br/>

<button id="chatHistoryAll">
1) 채팅내용 전체 불러오기 (클릭)
</button>

<br/><br/>

<form id="chatSearchedHistoryAll" >

<button type="submit">2) 검색하여 채팅내용 불러오기 (클릭) </button>
<br/><br/>

<label for="search-term">Search:</label>
<input type="text" id="search-term" name="searchTerm" placeholder="검색어를 입력하셈">

<label for="search-Condition">검색조건:</label>
<select id="search-Condition" name="searchCondition">
<!-- <option value="">선택</option> -->
<option value="chatNickname">닉네임</option>
<option value="chatDate">채팅날짜</option>
<option value="chatMsg">내용</option>
</select>

<!-- /api/chatTest?search-term="name에 입력한 것">&category="option value로 선택한 것" -->

</form>


<pre id="chatDisplay"></pre>

</body>
</html>
106 changes: 106 additions & 0 deletions chat-server-nodejs/mongoDB_lib_SJ.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// 1. mongoose 모듈 가져오기
var mongoose = require('mongoose');

async function mongooseSetup(){

// 2. testDB 세팅
mongoose.connect('mongodb://localhost:27017/testDB');

// 3. 연결된 testDB 사용
var db = mongoose.connection;

// 4. 연결 실패
db.on('error', function(){
console.log('Connection Failed!');
});
// 5. 연결 성공
db.once('open', function() {
console.log('Connected!');
});

// 6. Schema 생성
var chat = mongoose.Schema({
nickname : 'string',
'socket.id' : 'string',
chatMsg : 'string',
time : 'string'
});

// 7. 정의된 스키마를 객체처럼 사용할 수 있도록 model() 함수로 컴파일
var ModelChat = mongoose.model('Schema', chat);

return ModelChat;
}

async function mongooseReadOne(ModelChat, search){
// 9. 특정 데이터 조회
try {
console.log("디버깅 -> 검색조건", search);
const searchedChat = await ModelChat.findOne(search);
console.log('Chat found:', searchedChat);

return searchedChat;

} catch (err) {
console.error(err);
}
}

async function mongooseReadAll(ModelChat, search){
// 10. 전체 데이터 조회
try {
console.log("디버깅 -> mongooseReadAll 검색조건", search);
const searchedChats = await ModelChat.find(search);
console.log('Chats found number:', searchedChats.length);

return searchedChats;

} catch (err) {
console.error(err);
}
}

async function mongooseWrite(ModelChat,chat){
// 8. 데이터 저장
try {
const newChat = new ModelChat(chat);
await newChat.save();
console.log('Chat created:', newChat);
} catch (err) {
console.error(err);
}
}

async function mongooseUpdate(ModelChat){
// 11. 데이터 수정
try {
const updatedChat = await ModelChat.findOneAndUpdate(
{ name: 'Alice' },
{ age: 31 },
{ new: true } // 업데이트된 문서를 반환하도록 설정
);
console.log('Chat updated:', updatedChat);
} catch (err) {
console.error(err);
}
}

async function mongooseDelete(ModelChat){
// 12. 데이터 삭제
try {
const deletedChat = await ModelChat.findOneAndDelete({ name: 'Alice' });
console.log('Chat deleted:', deletedChat);
} catch (err) {
console.error(err);
}
}


module.exports = {
mongooseSetup,
mongooseWrite,
mongooseReadOne,
mongooseReadAll,
mongooseUpdate,
mongooseDelete
};
16 changes: 16 additions & 0 deletions chat-server-nodejs/node_modules/.bin/mime

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions chat-server-nodejs/node_modules/.bin/mime.cmd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading