Skip to content

Commit

Permalink
Merge pull request #10 from LeHiHo/feature/#4
Browse files Browse the repository at this point in the history
소켓 통신 구현
  • Loading branch information
LeHiHo authored Nov 9, 2023
2 parents 293292a + 3a8d614 commit e6f1e1e
Show file tree
Hide file tree
Showing 11 changed files with 149 additions and 109 deletions.
43 changes: 14 additions & 29 deletions src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const postJoin = async (joinData: JoinData) => {
};

export const getAllUsers = async (accessToken: string) => {
const res = await client.get('/users', {
const res = await client.get('users', {
headers: {
Authorization: `Bearer ${accessToken}`,
},
Expand All @@ -38,54 +38,39 @@ export const createGameRooms = async (
users: string[],
isPrivate: boolean,
) => {
const authData = {
name,
users,
isPrivate,
};
try {
const response = await axios.post(`${SERVER_URL}/chat`, authData, {
const res = await client.post(
`chat`,
{ name: name, users: users, isPrivate: isPrivate },
{
headers: {
'content-type': CONTENT_TYPE,
serverId: SERVER_ID,
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
} catch (error) {
console.log(error);
}
},
);
return res.data;
};

export const getAllGameRooms = async (accessToken: string) => {
const response = await axios.get(`${SERVER_URL}/chat/all`, {
const res = await client.get(`chat/all`, {
headers: {
'content-type': CONTENT_TYPE,
serverId: SERVER_ID,
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
return res.data;
};

export const participateGameRoom = async (
chatId: string,
accessToken: string,
) => {
const authData = {
chatId,
};
const response = await axios.patch(
`${SERVER_URL}/chat/participate`,
authData,
const res = await client.patch(
`chat/participate`,
{ chatId: chatId },
{
headers: {
'content-type': CONTENT_TYPE,
serverId: SERVER_ID,
Authorization: `Bearer ${accessToken}`,
},
},
);
console.log(response.data);
return response.data;
return res.data;
};
18 changes: 15 additions & 3 deletions src/api/socket.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import { SERVER_ID, CONTENT_TYPE, SERVER_URL } from '../constant';
import io from 'socket.io-client';
export const socketLogin = (accessToken: string) => {
import { io } from 'socket.io-client';
import { SERVER_URL, SERVER_ID } from '../constant';

export const loginSocket = (accessToken: string) => {
const socket = io(`${SERVER_URL}/server`, {
extraHeaders: {
Authorization: `Bearer ${accessToken}`,
serverId: SERVER_ID,
},
});
socket.on('connect', () => {
socket.emit('users-server');
});
socket.on('users-server-to-client', (data) => {
console.log('Received users from server:', data);
});

socket.on('message-to-client', (messageObject) => {
const usersArr = messageObject.users;
});

return socket;
};
12 changes: 10 additions & 2 deletions src/components/layout/checkGameRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import { allRoomState } from '../../states/atom';
import { getAllGameRooms, participateGameRoom } from '../../api';
import { useNavigate } from 'react-router-dom';

const POLLING_INTERVAL = 30000;

const CheckGameRoom = () => {
const token: any = localStorage.getItem('jwt');
const token: any = localStorage.getItem('accessToken');
const navigate = useNavigate();
const [allRooms, setAllRooms] = useRecoilState(allRoomState);
const fetchData = async () => {
Expand All @@ -19,7 +21,13 @@ const CheckGameRoom = () => {

useEffect(() => {
fetchData();
}, [allRooms.length]);
const pollingId = setInterval(() => {
fetchData();
}, POLLING_INTERVAL);
return () => {
clearInterval(pollingId);
};
}, [fetchData, setAllRooms]);

if (allRooms.length === 0) {
return <div>No rooms available or an error occurred.</div>;
Expand Down
30 changes: 30 additions & 0 deletions src/components/layout/offlineUserList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useRecoilValue } from 'recoil';
import { allUserState, onlineUserState } from '../../states/atom';
import { useEffect, useState } from 'react';

const OfflineUserList = () => {
const onLine = useRecoilValue(onlineUserState);
const all = useRecoilValue(allUserState);
const onlineUsers = onLine.users || [];
const differentNames = all.filter((element) => {
return !onlineUsers.includes(element.name);
});

const [offlineUsers, setOfflineUsers] = useState<string[]>([]);

useEffect(() => {
const offlineUserNames = differentNames.map((element) => element.name);
if (JSON.stringify(offlineUserNames) !== JSON.stringify(offlineUsers)) {
setOfflineUsers(offlineUserNames);
}
}, [differentNames, offlineUsers]);

return (
<div>
<div>OfflineUserList</div>
<div>Users: {offlineUsers.join(', ')}</div>
</div>
);
};

export default OfflineUserList;
41 changes: 0 additions & 41 deletions src/components/layout/onineUserList.tsx

This file was deleted.

17 changes: 17 additions & 0 deletions src/components/layout/onlineUserList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useRecoilValue } from 'recoil';
import { onlineUserState } from '../../states/atom';

const OnlineUserList = () => {
const socket = useRecoilValue(onlineUserState);

const users = socket.users || [];

return (
<div>
<div>OnlineUserList</div>
<div>Users: {users.join(', ')}</div>
</div>
);
};

export default OnlineUserList;
37 changes: 24 additions & 13 deletions src/components/layout/userList.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
import { useEffect } from 'react';
import { getAllUsers } from '../../api';
import { useRecoilState } from 'recoil';
import { allUserState } from '../../states/atom';
import { getAllUsers } from '../../api';

const POLLING_INTERVAL = 30000;

const UserList = () => {
const [allUsers, setAllUsers] = useRecoilState(allUserState);
// const [allRooms, setAllRooms] = useRecoilState(allRoomState);
const token: any = localStorage.getItem('jwt');
// const allUsers = useRecoilValue(allUserState);
console.log(allUsers);
useEffect(() => {
async function fetchData() {
try {
const allUsersData = await getAllUsers(token);
setAllUsers(allUsersData);
} catch (error) {
console.error('데이터 가져오기 오류:', error);

const fetchData = async () => {
try {
const token: any = localStorage.getItem('accessToken');
const allUsersData = await getAllUsers(token);
if (JSON.stringify(allUsersData.data) !== JSON.stringify(allUsers)) {
setAllUsers(allUsersData.data);
}
} catch (error) {
console.error('Error retrieving data:', error);
}
};

useEffect(() => {
fetchData();
}, []);

const pollingId = setInterval(() => {
fetchData();
}, POLLING_INTERVAL);

return () => {
clearInterval(pollingId);
};
}, [setAllUsers, fetchData]);

return (
<>
<div>AllUserList</div>
{allUsers.map((element, index) => (
<div key={index}>{element.name}</div>
))}
Expand Down
16 changes: 10 additions & 6 deletions src/pages/lobby/gameLobby.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import CreateGameRoom from '../../components/layout/createGameRoom';
import CheckGameRoom from '../../components/layout/checkGameRoom';
// import OnlineUserList from '../../components/layout/onineUserList';
// import UserList from '../../components/layout/userList';
import OnlineUserList from '../../components/layout/onlineUserList';
import UserList from '../../components/layout/userList';
import OfflineUserList from '../../components/layout/offlineUserList';
import { getAllUsers } from '../../api';

const GameLobby = () => {
const handleGetAllUsers = async (e: React.FormEvent) => {
e.preventDefault();

const token = localStorage.getItem('jwt');
const token = localStorage.getItem('accessToken');
if (!token) {
alert('인증 토큰이 없습니다. 로그인이 필요합니다.');
return;
Expand Down Expand Up @@ -39,15 +42,16 @@ const GameLobby = () => {
// }
// }


// fetchData();
// }, []);
return (
<>
{/* <UserList></UserList> */}
<UserList></UserList>
<br></br>
{/* <OnlineUserList /> */}
<OnlineUserList />
<br></br>
<OfflineUserList />
<br />
<CreateGameRoom></CreateGameRoom>
<br></br>
<CheckGameRoom></CheckGameRoom>
Expand Down
2 changes: 1 addition & 1 deletion src/pages/login/userJoin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ const UserJoin = () => {
const res = await postJoin(formData);
console.log(res);
alert('회원가입에 성공했습니다.');
navigate('/lobby');
navigate('/');
} catch (e: any) {
if (e.message === 'Request failed with status code 401') {
alert('중복된 아이디가 있습니다.');
Expand Down
Loading

0 comments on commit e6f1e1e

Please sign in to comment.