16. 스프링 - WebSocket 구축

1. 들어가기 전

   - 안드로이드와 연동 테스트를 위한 WebSocket 구축 테스트

   - 웹에서의 소켓 통신 부분은 따로 구성되지 않음

   - https://hwihyeon.tistory.com/31

 

안드로이드 - okHttp3/WebSocket 구축 및 서버 테스트

1. 들어가기 전  - 스프링 서버와 연동 테스트  - https://hwihyeon.tistory.com/30 16. 스프링 - WebSocket 구축 1. 들어가기 전  - 안드로이드와 연동 테스트를 위한 WebSocket 구축 테스트  - 웹에서의 소..

hwihyeon.tistory.com

 

2. dependency 추가

   - pom.xml 추가

<!-- ************************************************************ -->
<!--Websocket : com.fasterxml.jackson.core 와 같이 선언 -->
<!-- ************************************************************ -->

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0</version>
</dependency>

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

<!-- ************************************************************ -->

 

3. 환경 설정

   - src > main > webapp > WEB-INF > spring > root-context.xml

   - 하단의 namespaces에서 websocket 추가

   - src > main > webapp > WEB-INF > spring > appServlet > servlet-context.xml

   - class : webSocket 코드 위치

   - path : websocket로 접근할 주소 경로 (서버 설정에서 설정된 경로 이후에 붙는 경로)

<!-- WebSocket Handler 설정 -->
<beans:bean id="testHandler" class="com.hhkim.homepage.handler.testHandler"/>

<websocket:handlers>
    <websocket:mapping path="/websocket.message" handler="testHandler" />

    <!--  HttpSession 접근 설정 -->
    <websocket:handshake-interceptors>
        <beans:bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor" />
   </websocket:handshake-interceptors>

</websocket:handlers>

   - websocket 선언 오류 시 servlet-context.xml 상단의 beans:beans 부분 아래의 코드 추가 확인

xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.3.xsd"

 

4. 파일 생성

   - src > main > java > com.hhkim.homepage > handler > testHandler.java

package com.hhkim.homepage.handler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.context.annotation.SessionScope;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class testHandler extends TextWebSocketHandler {
	
	List<WebSocketSession> userList = new ArrayList<WebSocketSession>();
		
	//연결 성공 시
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		//생각나는 작업이 없어서...
	}
	
	//메시지 수신 시
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		System.out.println("수신 주소 확인 : " + session.getRemoteAddress().getAddress().getHostAddress());
		
		System.out.println("message 확인 : " + message);
		
		System.out.println("payload 확인 : " + message.getPayload());
		
		session.sendMessage(new TextMessage("서버 전송 테스트"));

	}
	
	//연결 종료 시
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		userList.remove(session);
		System.out.println("세션 연결 종료 : " + session + " : " + status);
		
	}

}

 

5. 테스트 결과 확인