React

[WebSocket] React로 WebSocket 구현하기(feat.Typescript)

연신내고독한늑대 2025. 1. 27. 20:00

이 전 포스팅에서 웹소켓이란 무엇이고, Java로 웹소켓 통신 구현하는 글들을 포스팅 했었는데 이번 글에서는 React로 클라이언트에서 어떻게 WebSocket을 구현하는지 소개하려고 합니다.

 

■ 필요한 라이브러리 설치

해당 구현에서는 다음 두 가지 라이브러리가 필요합니다:

  1. SockJS: WebSocket 연결을 위한 폴백(fallback) 라이브러리로, 브라우저 호환성을 보장합니다.
  2. @stomp/stompjs: STOMP 프로토콜을 기반으로 WebSocket 메시징을 쉽게 구현할 수 있게 해줍니다.
npm install sockjs-client @stomp/stompjs

 

■ 코드 구현

WebSocket 통신을 관리하기 위한 서비스 클래스입니다. 주요 코드 설명은 아래에 기술하였습니다.

## WebSocketService.ts

import { Client, Frame, IStompSocket } from "@stomp/stompjs";
import SockJS from "sockjs-client";

class WebSocketService {
  private client: Client;
  constructor() {
    this.client = new Client({
      webSocketFactory: () =>
        new SockJS("http://localhost:8080/ws", null, { withCredentials: true } as any) as unknown as IStompSocket,
      reconnectDelay: 5000,
      debug: (msg) => console.log(msg),
    });
  }

  connect(userId: String, onMessageReceived: (message: string) => void) {
    this.client.onConnect = (frame: Frame) => {
      console.log("Connected to WebSocket");
      this.client.subscribe(`/user/${userId}/queue/match`, (message) => {
        const body = message.body;
        onMessageReceived(body);
      });
    };

    this.client.activate(); // WebSocket 연결 시작
  }

  disconnect() {
    if (this.client.active) {
      this.client.deactivate();
      console.log("Disconnected from WebSocket");
    }
  }
}

export default new WebSocketService();

 

■ 주요 코드 설명

1. Client 객체 초기화

this.client = new Client({
  webSocketFactory: () =>
    new SockJS("http://localhost:8080/ws", null, { withCredentials: true } as any) as unknown as IStompSocket,
  reconnectDelay: 5000,
  debug: (msg) => console.log(msg),
});

 

  • webSocketFactory:
    • SockJS를 사용해 WebSocket 연결을 생성합니다.
    • "http://localhost:8080/ws"는 백엔드 WebSocket 엔드포인트를 가리킵니다.
    • withCredentials: true는 크로스 오리진 요청에서 쿠키와 인증 정보를 포함하도록 설정합니다.
  • reconnectDelay:
    • 연결이 끊어진 경우 5000ms(5초) 후에 자동으로 재연결합니다.
  • debug:
    • 디버그 메시지를 콘솔에 출력하여 WebSocket의 상태를 확인할 수 있습니다.

2. WebSocket 연결 및 메시지 구독

this.client.onConnect = (frame: Frame) => {
  console.log("Connected to WebSocket");
  this.client.subscribe(`/user/${userId}/queue/match`, (message) => {
    const body = message.body;
    onMessageReceived(body);
  });
};
  • onConnect:
    • WebSocket 연결이 성공하면 실행됩니다.
    • frame은 서버와의 초기 연결 상태를 나타내는 객체입니다.
  • subscribe:
    • 특정 목적지(/user/${userId}/queue/match)를 구독합니다.
    • 서버가 해당 경로로 메시지를 보내면, 콜백 함수(onMessageReceived)가 실행됩니다.

3. WebSocket 연결 종료

disconnect() {
  if (this.client.active) {
    this.client.deactivate();
    console.log("Disconnected from WebSocket");
  }
}

deactivate:

  • WebSocket 연결을 종료합니다.
  • 서버와의 연결이 안전하게 닫히며, 구독도 자동으로 해제됩니다.