Skip to content

Commit

Permalink
Merge pull request #39 from KTB-Hackathon-GoLang/dev
Browse files Browse the repository at this point in the history
Test: 소켓통신 테스트
  • Loading branch information
sayyyho authored Sep 6, 2024
2 parents 1fb9cf0 + feb70ab commit 618c005
Show file tree
Hide file tree
Showing 6 changed files with 154 additions and 22 deletions.
14 changes: 14 additions & 0 deletions src/api/chatJoin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { instance } from "./instance";

export const chatJoin = async () => {
try {
const res = await instance.post(`/api/chatrooms/join`, {
username: localStorage.getItem("username"),
chatroomUUID: localStorage.getItem("chatroomUUID"),
});
console.log(res);
return res;
} catch (err) {
console.log(err);
}
};
14 changes: 14 additions & 0 deletions src/api/postDetailAnother.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { instance } from "./instance";

export const postDetailAnother = async ({ relationship, chatroomDetails }) => {
try {
const res = await instance.post(`/api/chatrooms/details/join`, {
chatroomUUID: localStorage.getItem("chatroomUUID"),
chatroomDetails,
relationship,
});
return res;
} catch (err) {
console.log(err);
}
};
44 changes: 25 additions & 19 deletions src/pages/ChatPage/ChatPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import CHATTING_LAYOUT from "@/assets/chatLayout.svg";
import { useRef, useEffect, useState } from "react";
import useSpeechToText from "@/hooks/useSpeechToText";
import io from "socket.io-client";
import { useParams } from "react-router-dom";
import { useNavigate, useParams } from "react-router-dom";

export const ChatPage = () => {
const customInput = useRef();
Expand All @@ -15,6 +15,7 @@ export const ChatPage = () => {
const [messages, setMessages] = useState([]); // 메시지 배열
const socketRef = useRef();
const params = useParams();
const navigate = useNavigate();

const handleResizeHeight = () => {
if (customInput.current && recommendZone.current) {
Expand All @@ -33,35 +34,40 @@ export const ChatPage = () => {
}, [transcript]);

useEffect(() => {
// 소켓 연결 설정
socketRef.current = io(`https://api.golang-ktb.site/${params.room}`);
const username = localStorage.getItem("username");
localStorage.setItem("chatroomUUID", params.room);
if (!username) {
// 로컬 스토리지에 username이 없으면 로딩 페이지로 이동
navigate("/");
window.addEventListener("storage", (event) => {
if (event.key === "username" && event.newValue) {
navigate("/chatting/info/another");
}
});
} else {
// username이 이미 있는 경우 소켓 연결 설정
socketRef.current = io(`${import.meta.env.VITE_BASE_API}/${params.room}`);
const roomName = "y";
socketRef.current.emit("join", roomName);

// 특정 방에 조인
const roomName = "y";
socketRef.current.emit("join", roomName);
socketRef.current.on("message", (message) => {
setMessages((prevMessages) => [...prevMessages, message]);
});

// 메시지 수신 시 처리
socketRef.current.on("message", (message) => {
setMessages((prevMessages) => [...prevMessages, message]);
});

// 컴포넌트 언마운트 시 소켓 연결 해제
return () => {
socketRef.current.disconnect();
};
}, []);
return () => {
socketRef.current.disconnect();
};
}
}, [navigate, params.room]);

const handleSendMessage = () => {
const message = customInput.current.value;
if (message.trim()) {
// 내가 보낸 메시지 추가
const newMessage = { text: message, isMine: true };
setMessages((prevMessages) => [...prevMessages, newMessage]);

// 서버로 메시지 전송
socketRef.current.emit("send-message", newMessage);

// 입력창 비우기
customInput.current.value = "";
handleResizeHeight();
}
Expand Down
92 changes: 92 additions & 0 deletions src/pages/ChatSetting/ChatAnother.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import * as S from "./style";
import CHAT_LAYOUT from "@/assets/ChatLayout.png";
import REL_GOLANG from "@/assets/relationGolang.svg";
import { useState } from "react";
import { CHOOSE_TEXT } from "@/constant/chatSetting";
import { Header } from "@/components/Header/Header";
import { postDetailAnother } from "@/api/postDetailAnother";
import { chatJoin } from "@/api/chatJoin";
import { useNavigate } from "react-router-dom";

const relation = ["커플", "친구", "가족", "기타"];
const sendRelation = ["COUPLE", "FRIEND", "FAMILY", "ETC"];

export const ChatAnother = () => {
const navigate = useNavigate();
const [selectedBox, setSelectedBox] = useState([false, false, false, false]);
const [selectedNum, setSelectedNum] = useState(null);
const [chatDetails, setChatDetails] = useState(""); // 상태 추가

const handleSelect = (index) => {
const box = [false, false, false, false];
box[index] = true;
setSelectedBox(box);
setSelectedNum(index);
};

const handleInputChange = (event) => {
setChatDetails(event.target.value); // 입력된 값을 상태에 저장
};

const handleSubmit = async () => {
if (selectedNum !== null && chatDetails.trim() !== "") {
const res = await postDetailAnother({
chatroomDetails: chatDetails, // 입력된 값 사용
relationship: sendRelation[selectedNum],
});
if (res.data.success) {
console.log(
`https://golang-ktb.site/chatting/peer/${localStorage.getItem(
"chatroomUUID"
)}`
);
const res = await chatJoin();
if (res.data.success) {
navigate(`/chatting/peer/${localStorage.getItem("chatroomUUID")}`);
}
}
} else {
alert("모든 필드를 채워주세요.");
}
};

return (
<S.Layout
style={{
backgroundImage: `url(${CHAT_LAYOUT})`,
backgroundSize: "cover",
backgroundPosition: "center",
}}
>
<Header color="black" isBack={true}>
2인 채팅
</Header>

<img src={REL_GOLANG} />
{CHOOSE_TEXT.map((text, index) => (
<S.Text key={index}>{text}</S.Text>
))}
<S.RelationLayout>
{relation.map((text, index) => (
<S.SelectBox
onClick={() => handleSelect(index)}
key={index}
$isCheckd={selectedBox[index]}
>
{text}
</S.SelectBox>
))}
</S.RelationLayout>
<S.StyledInput
maxLength={300}
rows={7}
placeholder="상대와의 갈등 상황을 입력해주세요."
value={chatDetails}
onChange={handleInputChange} // 입력 핸들러 추가
/>
<S.CustomBtn onClick={handleSubmit}>
<S.Text color="white">Start Chatting</S.Text>
</S.CustomBtn>
</S.Layout>
);
};
2 changes: 0 additions & 2 deletions src/pages/ChatSetting/ChatInfo.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ export const ChatInfo = () => {
if (file) {
await postPdf(file);
navigate("relation");
} else {
alert("Please upload a PDF file.");
}
};

Expand Down
10 changes: 9 additions & 1 deletion src/pages/SharePage/Share.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ import * as S from "./style";
import { useEffect } from "react";
import { Header } from "@/components/Header/Header";
import LAYOUT from "@/assets/share.png";
import { useNavigate } from "react-router-dom";
const { Kakao } = window;

export const Share = () => {
const navigate = useNavigate();
const handleChatting = () => {
navigate(`/chatting/peer/${localStorage.getItem("chatroomUUID")}`);
};
const realUrl = "https://golang-ktb.site";

// 재랜더링시에 실행되게 해준다.
Expand Down Expand Up @@ -94,6 +99,9 @@ export const Share = () => {

<p
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
color: "#647DC3",
fontFamily: "Nunito",
fontSize: "20px",
Expand All @@ -105,7 +113,7 @@ export const Share = () => {
</p>
</div>
</S.Box>
<S.CustomBtn>
<S.CustomBtn onClick={handleChatting}>
<S.Text color="white">채팅방 입장하기</S.Text>
</S.CustomBtn>
</S.Layout>
Expand Down

0 comments on commit 618c005

Please sign in to comment.