Skip to content

Commit

Permalink
Merge pull request #121 from MOVIEJOJO7/Feature/#120
Browse files Browse the repository at this point in the history
Feat: 소켓 연결 로직 개선
  • Loading branch information
JitHoon authored Nov 16, 2023
2 parents 0e4f616 + 2bd1a02 commit 1d0cdaf
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 42 deletions.
42 changes: 23 additions & 19 deletions Components/Chat/ChatRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,11 @@ const ChatRoom = ({
fetchChatUsers();
}, [accessToken, chatId]);

// 'fetch-messages' 이벤트 등록
// 'messages-to-client' 이벤트 등록
useEffect(() => {
if (socket?.connected) {
socket.off('messages-to-client');

if (socket.connected) {
socket.emit('fetch-messages');

socket.on('messages-to-client', (messagesObject) => {
Expand All @@ -63,46 +65,49 @@ const ChatRoom = ({
}

return () => {
socket?.off('messages-to-client');
socket.off('messages-to-client');
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [socket.connected]);
}, [socket]);

// message-to-client 이벤트 등록
// 'message-to-client' 이벤트 등록
useEffect(() => {
if (socket?.connected) {
socket.off('message-to-client');

if (socket.connected) {
socket.on('message-to-client', (responseData) => {
setMessages((prevMessages) => [...prevMessages, responseData]);
});
}

return () => {
socket?.off('message-to-client');
socket.off('message-to-client');
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [socket.connected]);
}, [socket]);

// join 이벤트 등록
// 'join' 이벤트 등록
useEffect(() => {
if (socket?.connected) {
socket.off('join');

if (socket.connected) {
socket.on('join', (responseData) => {
setChatUsers([...chatUsers, ...responseData.users]);

if (responseData.users[0] !== userId) {
Swal.fire(`${responseData.leaver} 님이 퇴장하셨습니다.`);
Swal.fire(`${responseData.users[0]} 님이 입장하셨습니다.`);
}
});
}

return () => {
socket.off('join');
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chatUsers, socket.connected]);
}, [chatUsers, socket, userId]);

// leave 이벤트 등록
useEffect(() => {
if (socket?.connected) {
socket.off('leave');

if (socket.connected) {
socket.on('leave', (responseData) => {
setChatUsers([...chatUsers, ...responseData.users]);

Expand All @@ -115,13 +120,12 @@ const ChatRoom = ({
return () => {
socket.off('leave');
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chatUsers, socket.connected]);
}, [chatUsers, socket, userId]);

// 서버로 메시지 전송
const sendMessage = () => {
if (newMessage.trim() !== '') {
socket?.emit('message-to-server', newMessage);
socket.emit('message-to-server', newMessage);
setNewMessage('');
}
};
Expand Down
72 changes: 49 additions & 23 deletions app/chat/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,67 @@

import { useSearchParams } from 'next/navigation';
import { getCookie } from '@/Components/Login/Cookie';
import { io } from 'socket.io-client';
import { io, Socket } from 'socket.io-client';
import { useEffect, useState } from 'react';
import ChatRoom from '@/Components/Chat/ChatRoom';
import { useEffect } from 'react';

const Chat = ({ params }: { params: { id: string } }) => {
const chatId = params.id;
const query = useSearchParams();
const privateValue = query?.get('isPrivate') as string;
const accessToken = getCookie('accessToken');

const socket = io(`https://fastcampus-chat.net/chat?chatId=${chatId}`, {
extraHeaders: {
Authorization: `Bearer ${accessToken}`,
serverId: process.env.NEXT_PUBLIC_SERVER_ID as string,
},
});
const [isConnect, setIsConnect] = useState(false);
const [chatSocket, setchatSocket] = useState<Socket | null>(null);

// 소켓 연결 시도
useEffect(() => {
if (isConnect === true) return;

const socket = io(`https://fastcampus-chat.net/chat?chatId=${chatId}`, {
extraHeaders: {
Authorization: `Bearer ${accessToken}`,
serverId: process.env.NEXT_PUBLIC_SERVER_ID as string,
},
});

socket.off('connect');
socket.off('connect_error');
socket.off('disconnect');

socket.on('connect', () => {
setIsConnect(true);
setchatSocket(socket);
});

socket.on('disconnect', () => {
setchatSocket(null);
setIsConnect(false);
});

socket.on('connect_error', () => {
setchatSocket(null);
throw new Error();
});
}, [accessToken, isConnect, chatId]);

useEffect(() => {
return () => {
socket.disconnect();
chatSocket?.disconnect();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return (
<>
<div className="h-screen overflow-y-scroll">
<ChatRoom
socket={socket}
chatId={chatId}
privateValue={privateValue}
accessToken={accessToken}
/>
</div>
</>
}, [chatSocket]);

return chatSocket ? (
<div className="h-screen overflow-y-scroll">
<ChatRoom
socket={chatSocket}
chatId={chatId}
privateValue={privateValue}
accessToken={accessToken}
/>
</div>
) : (
<></>
);
};

Expand Down

0 comments on commit 1d0cdaf

Please sign in to comment.