🛠️ 트러블 슈팅

[트러블 슈팅] WebSocket 연결 시의 Connection closed to.... 해결

밈98 2025. 1. 12. 17:14

🛠️ WebSocket 연결 시의 Connection closed to.... 문제 해결

 

내 프론트코드는 이렇게 연결을 할 수 있도록 작성되어있다.

const connectWebSocket = () => {
        try {
            console.log('Attempting to connect to WebSocket...');

            // Create a WebSocket factory function
            const wsFactory = () => {
                return new SockJS('http://localhost:8070/ws', null, {
                    transports: ['websocket'],
                    debug: true
                });
            };
            
            // Pass the factory function to Stomp.over
            const client = Stomp.over(wsFactory);
            
            client.debug = (str) => {
                console.log('STOMP:', str);
            };

 

백엔드에서는 연동이 잘 되었지만

프론트에서는 Connection closed to ... 로 계속 접속이 안되는 상황이었다.

 

이 문제는 리액트 초보자였기에 벌어진 일이었다...

 

 

최근 React랑 vite를 사용해서 프로젝트를 구축하는데

나는 백엔드 개발자다보니 React에 약한 사람이었다.

💡 해결한 코드

index.html 
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
  </head>
  <body>
    <div id="root"></div>
    <script>
      // global 객체 정의
      const global = globalThis;
    </script>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

 

vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  define: {
    global: 'window', // 브라우저에서 global 변수를 빈 객체로 설정
  },
})

 

문제원인

  • Vite는 기본적으로 Node.js 환경의 global 객체를 제공하지 않는다.
  • React 프로젝트에서 WebSocket 통신을 위해 사용하는 일부 라이브러리 (SockJS, STOMP.js)는 global 객체에 의존할 수 있다.

 

vite.config.js에서 define 옵션을 사용해 global 객체를 명시적으로 설정하지 않았기때문에 벌어진 일이었다.

그랬기때문에 빈값이어서 계속 접속이 안되었었던 상황이었다.

 

React+vite에서는 global 객체를 올바르게 설정해야 WebSocket 통신이 정상적으로 작동한다는 것을 배울 수 있었다!