Skip to content

Commit

Permalink
Merge pull request #83 from Hanjuri/feature/#49
Browse files Browse the repository at this point in the history
Feature/#49 채팅방 수정
  • Loading branch information
Hanjuri authored Sep 9, 2024
2 parents 739f973 + a96da18 commit 0e9e5a1
Show file tree
Hide file tree
Showing 10 changed files with 415 additions and 88 deletions.
6 changes: 0 additions & 6 deletions .idea/inspectionProfiles/Project_Default.xml

This file was deleted.

2 changes: 1 addition & 1 deletion src/api/ChatMessageCall.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const getChatMessages = async (roomUUID, page = 0, size = 10) => {
});
return response.data;
} catch (error) {
console.error("Error fetching chat messages!:", error.message);
console.error("채팅방 메세지 불러오기 실패:", error.message);
throw error;
}
};
14 changes: 14 additions & 0 deletions src/api/JoinInfoPost.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// src/utils/api.js
import { instance } from "./instanceAuth"; // 설정된 Axios 인스턴스 임포트

export async function postMemberData(data) {
const url = `/api/auth/member?name=${encodeURIComponent(data.koreanName)}`;

try {
const response = await instance.post(url, data); // Axios 인스턴스 사용
return response.data; // 서버로부터 받은 응답 데이터를 반환
} catch (error) {
console.error("회원정보 보내기 실패:", error);
throw error; // 오류를 호출자에게 다시 던짐
}
}
29 changes: 29 additions & 0 deletions src/api/instanceAuth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import axios from "axios";

// Axios 인스턴스 생성
export const instance = axios.create({
baseURL: import.meta.env.VITE_AUTH_BASE_URL,
withCredentials: true,
headers: {
"Content-Type": "application/json",
},
timeout: 10000, // 10초 타임아웃 설정
});

// 요청 인터셉터 추가
instance.interceptors.request.use(
(config) => config,
(error) => Promise.reject(error)
);

// 응답 인터셉터 추가
instance.interceptors.response.use(
(response) => response,
(error) => {
if (error.code === "ECONNABORTED") {
console.log("Request timeout");
window.location.href = "/error"; // 타임아웃 시 에러 페이지로 리디렉션
}
return Promise.reject(error);
}
);
2 changes: 1 addition & 1 deletion src/components/Common/Header.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ function Header() {
<styles.NavBar>
<styles.NavItem href="/">카부 게시판</styles.NavItem>
<styles.NavItem href="/">카부 프로젝트</styles.NavItem>
<styles.NavItem href="/">카부 편의</styles.NavItem>
<styles.NavItem href="/join">카부 편의</styles.NavItem>
<styles.NavItem href="/chat">카부 커넥션</styles.NavItem>
</styles.NavBar>
</styles.HeaderSubContainer>
Expand Down
4 changes: 2 additions & 2 deletions src/pages/Homepage/HomePage.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React from "react";
import Layout from "../../components/Common/Layout";
import ChatMain from "../../pages/chat/ChatMain";

function HomePage() {
return (
<Layout children={ChatMain}>
<Layout>
<h1>햄스터</h1>
<h1>햄스터</h1>
<h1>햄스터</h1>
Expand Down
167 changes: 89 additions & 78 deletions src/pages/chat/ChatRoom.jsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import React, { useEffect, useState } from "react";
import io from "socket.io-client";
import * as Stomp from 'stompjs';
import SockJS from "sockjs-client";
import * as styles from "./styled/ChatRoom.styled";
import Text from "../../components/Common/Text";
import ChatMessage from "./ChatMessage.jsx";
import { getChatMessages } from "../../api/ChatMessageCall.js";

const ChatRoom = (props) => {
const { uuid, name } = props;
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState("");
const [socket, setSocket] = useState(null);
const { uuid, name } = props;
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState("");
const [stompClient, setStompClient] = useState(null);

const currentUsername = "pjh2"; // 현재 사용자를 pjh2로 가정
const currentUsername = "pjh2"; // 현재 사용자를 pjh2로 가정

const roomId = props.uuid;

Expand Down Expand Up @@ -63,80 +64,90 @@ const ChatRoom = (props) => {
]);
});

return () => {
if (newSocket) {
newSocket.disconnect();
console.log("WebSocket 연결 해제 되었습니다!");
}
};
}, [uuid]); // uuid 변경될 때마다 재연결

const sendMessage = () => {
if (message.trim() === "" || !socket || !uuid) {
return;
}

const chatMessage = {
chatRoomUUID: uuid,
username: currentUsername, // 현재 접속한 사용자
nickname: "UserNickName",
message: message,
return () => {
if (client) {
client.disconnect(() => {
console.log("WebSocket 연결 해제 되었습니다!");
});
}
};
}, [uuid]); // uuid 변경될 때마다 재연결

const sendMessage = () => {
if (message.trim() === "" || !stompClient || !uuid) {
return;
}

const chatMessage = {
chatRoomUUID: uuid,
username: currentUsername, // 현재 접속한 사용자
nickname: "UserNickName",
message: message,
};

stompClient.send("/pub/messages", {}, JSON.stringify(chatMessage));

setMessages(prevMessages => {
if (Array.isArray(prevMessages)) {
return [
...prevMessages,
{
id: Date.now(), // 임시로 고유 ID를 부여
user: chatMessage.username,
text: chatMessage.message,
time: new Date().toLocaleTimeString(),
isCurrentUser: true, // 현재 사용자가 보낸 메시지이므로 true
}
];
} else {
return [{
id: Date.now(),
user: chatMessage.username,
text: chatMessage.message,
time: new Date().toLocaleTimeString(),
isCurrentUser: true,
}];
}
});

setMessage("");
};

socket.emit("message", chatMessage);

setMessages((prevMessages) => [
...prevMessages,
{
id: Date.now(), // 임시로 고유 ID를 부여
user: chatMessage.username,
text: chatMessage.message,
time: new Date().toLocaleTimeString(),
isCurrentUser: true, // 현재 사용자가 보낸 메시지이므로 true
},
]);

setMessage("");
};

return (
<styles.TotalWrapper>
<styles.NameWrapper>
<Text
value={props.name}
fontFamily="KakaoBold"
fontSize={45}
color="#000"
>
{name}
</Text>
</styles.NameWrapper>
<styles.ChatRoomWrapper>
{Array.isArray(messages) &&
messages.map((each, id) => (
<ChatMessage
key={each.id}
name={each.username}
message={each.message}
time={each.time}
isCurrentUser={each.isCurrentUser}
/>
))}
</styles.ChatRoomWrapper>

<styles.BottomWrapper>
<styles.InputWrapper>
<styles.Input
placeholder={"메세지를 입력하세요..."}
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && sendMessage()}
></styles.Input>
</styles.InputWrapper>
<styles.SendButton onClick={sendMessage}>{">"}</styles.SendButton>
</styles.BottomWrapper>
</styles.TotalWrapper>
);
return (
<styles.TotalWrapper>
<styles.NameWrapper>
<Text
value={props.name}
fontFamily="KakaoBold"
fontSize={45}
color="#000"
>{name}</Text>
</styles.NameWrapper>
<styles.ChatRoomWrapper>
{Array.isArray(messages) && messages.map((each, id) => (
<ChatMessage
key={each.id}
name={each.username}
message={each.message}
time={each.time}
isCurrentUser={each.isCurrentUser}
/>
))}
</styles.ChatRoomWrapper>

<styles.BottomWrapper>
<styles.InputWrapper>
<styles.Input
placeholder={"메세지를 입력하세요..."}
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && sendMessage()}
></styles.Input>
</styles.InputWrapper>
<styles.SendButton onClick={sendMessage}>{'>'}</styles.SendButton>
</styles.BottomWrapper>
</styles.TotalWrapper>
);
};

export default ChatRoom;
Loading

0 comments on commit 0e9e5a1

Please sign in to comment.