Skip to content

Commit

Permalink
socketIO setting
Browse files Browse the repository at this point in the history
  • Loading branch information
yeoularu committed Apr 30, 2024
1 parent 318e5ea commit ec58a54
Show file tree
Hide file tree
Showing 10 changed files with 188 additions and 100 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"react-kakao-maps-sdk": "^1.1.21",
"react-redux": "^8.1.3",
"react-router-dom": "^6.16.0",
"socket.io-client": "^4.7.5",
"vite-plugin-svgr": "^2.4.0"
},
"devDependencies": {
Expand Down
68 changes: 68 additions & 0 deletions pnpm-lock.yaml

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

37 changes: 37 additions & 0 deletions src/app/SocketContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { createContext, useEffect, useRef } from "react";
import io, { Socket } from "socket.io-client";
import { useDispatch, useSelector } from "react-redux";
import { messageReceived } from "app/socketSlice";
import { api } from "./api";
import { selectCurrentToken } from "./authSlice";

export const SocketContext = createContext<Socket | null>(null);

export const SocketProvider = ({ children }: { children: JSX.Element }) => {
const dispatch = useDispatch();
const token = useSelector(selectCurrentToken);
const { data: chatRooms } = api.useGetMyChatRoomsQuery(null);
const socketRef = useRef<Socket | null>(null);

useEffect(() => {
if (!socketRef.current) {
socketRef.current = io(import.meta.env.VITE_WEBSOCKET_URL, {
query: { token },
});
}

socketRef.current.on("message", (topic, message) => {
dispatch(messageReceived({ topic, body: message }));
});

return () => {
socketRef.current?.disconnect();
};
}, [token, dispatch, chatRooms]);

return (
<SocketContext.Provider value={socketRef.current}>
{children}
</SocketContext.Provider>
);
};
80 changes: 0 additions & 80 deletions src/app/StompContext.tsx

This file was deleted.

12 changes: 6 additions & 6 deletions src/app/stompSlice.ts → src/app/socketSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ interface Message {
body: string;
}

interface StompState {
interface SocketState {
messages: Message[];
}

const initialState: StompState = {
const initialState: SocketState = {
messages: [],
};

export const stompSlice = createSlice({
name: "stomp",
export const socketSlice = createSlice({
name: "socket",
initialState,
reducers: {
messageReceived: (state, action: PayloadAction<Message>) => {
Expand All @@ -23,6 +23,6 @@ export const stompSlice = createSlice({
},
});

export const { messageReceived } = stompSlice.actions;
export const { messageReceived } = socketSlice.actions;

export default stompSlice.reducer;
export default socketSlice.reducer;
4 changes: 2 additions & 2 deletions src/app/store.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { configureStore } from "@reduxjs/toolkit";
import { api } from "./api";
import stompReducer from "./stompSlice";
import socketReducer from "./socketSlice";
import { useDispatch } from "react-redux";
import authReducer from "./authSlice";
import sseReducer from "./sseSlice";
Expand All @@ -9,7 +9,7 @@ import layoutReducer from "components/ui/layoutSlice";
export const store = configureStore({
reducer: {
[api.reducerPath]: api.reducer,
stomp: stompReducer,
socket: socketReducer,
auth: authReducer,
sse: sseReducer,
layout: layoutReducer,
Expand Down
30 changes: 23 additions & 7 deletions src/components/chat/ChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { IconSend } from "@tabler/icons-react";
import { useForm } from "@mantine/form";
import { api } from "app/api";
import dayjs from "dayjs";
import { StompContext } from "app/StompContext";
import { SocketContext } from "app/SocketContext";

export function ChatInput({ roomId }: { roomId: number }) {
const { data } = api.useGetMyInfoQuery(null);
Expand All @@ -24,7 +24,26 @@ export function ChatInput({ roomId }: { roomId: number }) {
},
});

const { client } = useContext(StompContext);
const socket = useContext(SocketContext);

// const handleSend = (text: string) => {
// if (text !== "") {
// const message = {
// type: "TALK",
// roomId,
// text,
// senderId: data?.userId,
// sendTime: dayjs().toISOString(),
// };

// if (!socket) return console.error("WebSocket is not connected");

// socket.publish({
// destination: "/pub/chat/room/" + String(roomId),
// body: JSON.stringify(message),
// });
// }
// };

const handleSend = (text: string) => {
if (text !== "") {
Expand All @@ -36,12 +55,9 @@ export function ChatInput({ roomId }: { roomId: number }) {
sendTime: dayjs().toISOString(),
};

if (!client) return console.error("WebSocket is not connected");
if (!socket) return console.error("Socket is not connected");

client.publish({
destination: "/pub/chat/room/" + String(roomId),
body: JSON.stringify(message),
});
socket.emit("chat message", message); // 'chat message' 이벤트로 메시지 전송
}
};

Expand Down
4 changes: 2 additions & 2 deletions src/components/chat/ChatRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { redirect, useParams } from "react-router-dom";
import { api } from "app/api";
import ChatMessageCard from "./ChatMessageCard";
import { useEffect, useMemo, useRef, useState } from "react";
import { ChatMessage, ChatRoom } from "types";
import type { ChatMessage, ChatRoom } from "types";
import dayjs from "dayjs";
import { ChatHeader } from "./ChatHeader";

Expand Down Expand Up @@ -34,7 +34,7 @@ export default function ChatRoom() {
}
}, [isSuccess, data, id, isError, error]);

const newMessages = useSelector((state: RootState) => state.stomp.messages)
const newMessages = useSelector((state: RootState) => state.socket.messages)
.filter((message) => message.topic === "/topic/" + id)
.map((message) => {
return JSON.parse(message.body);
Expand Down
6 changes: 3 additions & 3 deletions src/components/ui/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {
import { useEffect } from "react";
import { SseProvider } from "app/SseContext";
import { EditUserInfoModal } from "components/user/EditUserInfoModal";
import { StompProvider } from "app/StompContext";
import { SocketProvider } from "app/SocketContext";

const headerLinks = [
{
Expand Down Expand Up @@ -92,7 +92,7 @@ export default function Layout() {
}

return (
<StompProvider>
<SocketProvider>
<SseProvider>
<AppShell
styles={{
Expand Down Expand Up @@ -169,6 +169,6 @@ export default function Layout() {
<FloatingActionButton />
</AppShell>
</SseProvider>
</StompProvider>
</SocketProvider>
);
}
Loading

0 comments on commit ec58a54

Please sign in to comment.