프로젝트/공연 예약 플랫폼

Spring Framework - 웹 소켓

sm_leaf25 2025. 1. 6. 01:10

1. 웹 소켓이란?

- 사용자의 브라우저와 서버 사이의  통신을 위한 양방향 통신 규격 

- 실시간 작업을 할 수 있다. (채팅, 시세변동, 실시간 알림 기능 등)

 

2. 소켓 사용 방법

  1) pom.xml에 웹 소켓 dependency( 의존성 )을 추가

       - dependencies :

          프로젝트에서 사용할 라이브러리들의 정보를 담는 구간 의존성 라이브러리

          기본적으로 필요한 라이브러리들이 등록되어 있고 추가적으로 필요한 라이브러리가 있다면 dependency를 추가하여 사용

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

- Maven에서 의존성 관리 기능을 통해 라이브러리 버전과 관련된 작업을 자동으로 처리해 주기 때문에 변수(프로퍼티) 활용

 

  2) servlet-context에 웹소켓 서버 등록

<!-- 웹소켓 서버 등록 -->
<!-- id:해당 서버를 부를 이름 , class : 해당 서버의 풀경로 -->
<beans:bean id="chatServer" class="com.kh.show.common.websocket.server.WebSocketServer"/>
	
<!-- 접속을 받아줄 대상을 지정하는 작업 -->
<!-- allowed-origins : 어떤 요청 경로를 허용할것인지 설정 -->
<websocket:handlers allowed-origins="http://localhost:8889/spring">
	<!-- handler : 어떠한 서버가 요청을 받아줄것인지 설정 -->
	<!-- 웹 소켓의 경로는 http://localhost:8889/spring/chat 이 아니라 
		 ws://localhost:8889/spring/chat 이다. -->
		
    <websocket:mapping handler="chatServer" path="/chat"/>
		
	<!-- Http통신으로 요청되어진 HttpSession 정보를 가지고 오기 위한 설정 
       	 -- 로그인한 회원의 정보 등 Http 통신에서 정보를 가지고 와야 할 경우 설정 -->
	<websocket:handshake-interceptors>
		<beans:bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor"></beans:bean>
	</websocket:handshake-interceptors>
</websocket:handlers>

 

 

  3)  websocket 클래스 (websocket 관련 메소드 구현)