Spring

Spring Boot + build.gradle + WebSocket 연동

주피터0410 2023. 7. 17. 17:18

build.gradle 에서 dependencies websocket 추가-

    implementation 'org.springframework.boot:spring-boot-starter-websocket'

build.gradle 원본 소스(버젼마다 호환성의 문제로 전체 source)

plugins {
    id 'org.springframework.boot' version '2.6.1'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.coforward'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
    all {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
}

repositories {
    mavenCentral()
}

dependencies {
    // define a BOM and its version
    implementation(platform("com.squareup.okhttp3:okhttp-bom:4.9.2"))
    implementation("com.squareup.okhttp3:okhttp")
    implementation("com.squareup.okhttp3:logging-interceptor")

    implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.2'
    implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.2'
    implementation group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.2'

    implementation 'org.springframework.boot:spring-boot-starter-freemarker'
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    //implementation 'org.springframework.boot:spring-boot-starter-security'
    //implementation 'org.springframework.security:spring-security-test'
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.0'
    implementation 'org.springframework.boot:spring-boot-starter-log4j2'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-websocket'
    
    implementation 'org.bgee.log4jdbc-log4j2:log4jdbc-log4j2-jdbc4.1:1.16'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation('nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect')
    implementation group: 'com.github.zhanhb', name: 'thymeleaf-layout-dialect', version: '2.4.1'

    //providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'

    implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
    implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
    implementation 'org.projectlombok:lombok:1.18.16'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

build.gradle 화일이 수정되면 코끼리 모양을 클릭해서 Gradle change 해준다.

 

WebSocket 클래스와 WebSocketConfig 클래스의 패키지 위치

 

webSocket 의 URL 매칭할 @ServerEndpoint 어노테이션 클래스 생성

package com.coforward.dev.controller;

import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

@Service
@ServerEndpoint("/webSocket")
public class WebSocket {

    @OnMessage
    public void onMessage(String msg, Session session) throws Exception{
        System.out.println("/webSocket onMessage...........");
    }

    @OnOpen
    public void onOpen(Session s) {
        System.out.println("/webSocket open...........");
    }

    @OnClose
    public void onClose(Session s) {
        System.out.println("/webSocket onClose...........");
    }
}

1) onOpen 메소드

/webSocket의 url로 서버에 접속하게 되면 실행

 

2) onMessage 메소드

클라이언트로부터 메세지가 전달되면 실행

 

3) onClose 메소드

클라이언트가 url을 바꾸거나 브라우저를 종료하게 되면 실행

 

WebSocketConfig Bean 생성

package com.coforward.dev.controller;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Component
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

 

TestController 화일에 GetMapping 으로 websocket html 메소드 추가

패키지 구조

package com.coforward.dev.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Controller
@RequestMapping("/test/")
@RequiredArgsConstructor
public class TestController {

    @GetMapping("/websocket")
    public String websocket(HttpServletRequest request, HttpServletResponse response) {

        HttpSession session = request.getSession();
        System.out.println("웹소켓 테스트 컨트롤러...................................");

        // test폴더에 websocket.html화일로 구성
        return "test/websocket";
    }
}

 

websocket.html 구조 및 내용

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<script>
    const webSocket = new WebSocket("ws://localhost:8080/webSocket");

    // 웹 소켓 연결 이벤트
    webSocket.onopen = function () {
        alert("웹소켓 서버와 연결에 성공했습니다.");
    };

    // 웹 소켓 메세지 수신
    webSocket.onmessage = function (event) {
        alert(event.data);
    };

    // 웹 소켓 연결 종료
    webSocket.onclose = function () {
        alert("웹소켓 서버와 연결이 종료되었습니다.");
    };

    // 오류 발생
    webSocket.onerror = function (error) {
        console.log(error);
    };
</script>
<body>

</body>
</html>