생각정리/사이드 프로젝트

사이드 프로젝트 : 중고 거래 플랫폼 - 웹 소켓 프론트엔드 설정

생각중임 2024. 1. 28. 19:47

채팅방 입장 

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