채팅방 입장
useEffect(() => {
// 채팅방정보 API로 받아오기
const getRoom = async () => {
const response = await getChatRoom(roomId);
if (response?.status === 200) {
setChatRoomState(response.data);
} else {
console.log("실패");
}
};
getRoom();
// 채팅방 메시지 내역 API로 받아오기
const ChatHistory = async () => {
const response = await getChatHistory(roomId);
if (response?.status === 200) {
const messages = response.data;
setMessages(messages);
} else {
console.error("채팅 내역 로드 실패");
}
};
ChatHistory();
const client = new Client({
brokerURL: `${process.env.REACT_APP_BROKER_URL}/chat/websocket`,
debug: str => {
console.log(str);
},
reconnectDelay: 5000,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
onConnect: () => {
client.subscribe(
`/topic/chatroom/${roomId}`,
(message: IMessage) => {
const msg: ChatMessageResponse = JSON.parse(message.body);
setMessages((prevMessages) => [...prevMessages, msg]);
},
);
},
onStompError: frame => {
console.error(frame);
},
});
client.activate();
setStompClient(client);
return () => {
client.deactivate();
};
}, [roomId]);
메시지 보내기
const onClick = () => {
if (stompClient && newMessage) {
const chatMessage: ChatMessageReqeust = {
roomId: parseInt(roomId || ""),
message: newMessage,
userId: userId,
};
stompClient.publish({
destination: `/app/sendMessage`,
body: JSON.stringify(chatMessage)
});
setNewMessage("");
}
};
발생한 문제들
Stomp.over
const client = useRef<CompatClient | null>(null);
const socket = new SockJS(`${process.env.REACT_APP_SERVER_URL}/chat`);
// SockJS 클라이언트 객체 socket를 STOMP 프로토콜로 오버랩하여 client.current에 할당
client.current = Stomp.over(socket);
- client.current에 정상적이지 않은 값이 들어가는 오류 발생한다.
- 소켓을 연락할때 이제는 재연결 옵션을 등록을 해야한다고 찾았다.
- 그리고 문법 자체도 변경을 권고하고 있었다.
StompJs.Client
const socket = new SockJS(`${process.env.REACT_APP_SERVER_URL}/chat`);
client.current = new StompJs.Client({
webSocketFactory: () => socket, // 프록시를 통한 접속
debug: str => {
console.log(str);
},
reconnectDelay: 5000, // 자동 재 연결
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
});
- 재연결 옵션을 넣으면서 StompJs.client로 문법을 적용을 하는데, StompJs를 사용할 수 없다는 오류가 발생한다.
- 지금 사용하는 환경설정과 맞지 않는 환경설정이 문제로 파악되었다.
https://stomp-js.github.io/guide/stompjs/using-stompjs-v5.html
Using StompJs v5+
You can find samples at https://github.com/stomp-js/samples/.
stomp-js.github.io
해결책
stompjs 깃을 찾아 최종변경된 사용방법을 찾았다 !
<!--
JSPM Generator Import Map
Edit URL: https://generator.jspm.io/#U2NgYGBkDM0rySzJSU1hcCguyc8t0AeTWcUO5noGega6SakliaYAYTzJAykA
-->
<script type="importmap">
{
"imports": {
"@stomp/stompjs": "https://ga.jspm.io/npm:@stomp/stompjs@7.0.0/esm6/index.js"
}
}
</script>
<!-- ES Module Shims: Import maps polyfill for modules browsers without import maps support (all except Chrome 89+) -->
<script
async
src="https://ga.jspm.io/npm:es-module-shims@1.5.1/dist/es-module-shims.js"
crossorigin="anonymous"
></script>
<script type="module">
import { Client } from '@stomp/stompjs';
const client = new Client({
brokerURL: 'ws://localhost:15674/ws',
onConnect: () => {
client.subscribe('/topic/test01', message =>
console.log(`Received: ${message.body}`)
);
client.publish({ destination: '/topic/test01', body: 'First Message' });
},
});
client.activate();
</script>
https://github.com/stomp-js/stompjs
GitHub - stomp-js/stompjs: Javascript and Typescript Stomp client for Web browsers and node.js apps
Javascript and Typescript Stomp client for Web browsers and node.js apps - GitHub - stomp-js/stompjs: Javascript and Typescript Stomp client for Web browsers and node.js apps
github.com
'생각정리 > 사이드 프로젝트' 카테고리의 다른 글
사이드 프로젝트 : 중고 거래 플랫폼 - 게시글 관련 쿼리 최적화 (0) | 2024.05.17 |
---|---|
사이드 프로젝트 : 중고 거래 플랫폼 - 게시글 좋아요 레디스 활용 (0) | 2024.02.20 |
사이드 프로젝트 : 중고 거래 플랫폼 - 웹 소켓 백엔드 설정 (0) | 2024.01.26 |
사이드 프로젝트 : 중고 거래 플랫폼 - 채팅 (0) | 2024.01.24 |
사이드 프로젝트 : 중고 거래 플랫폼 - 리엑트 로그인, 회원가입 (0) | 2024.01.19 |