'frontend'에 해당되는 글 1건

웹소켓 연결 테스트 소스

1. pom.xml 에 웹소캣 관련 라이브러리 추가

<!--  웹소캣 관련 내용 -->
		<!-- Spring WebSocket 의존성 -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-websocket</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>
		
		<!-- Spring Messaging 의존성 -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-messaging</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>
		
		<!-- (선택 사항) STOMP 프로토콜 지원을 위한 의존성 -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-messaging</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>

2. servlet-context.xml 관련내용 추가 

<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd"
	>


<context:component-scan base-package="com.soft.websocket" />
	
	<websocket:handlers>
        <websocket:mapping path="/testwebsockethandler01" handler="WebSocketHandler01"/>
    </websocket:handlers>
    
    <!-- WebSocket 핸들러 Bean 등록 -->
    <beans:bean id="WebSocketHandler01" class="com.soft.websocket.Test_webSocketHandler"/>
	<!-- 스케쥴러파일이 존재하는 패키지 설정 -->

xmlns:websocket="http://www.springframework.org/schema/websocket" 웹소캣 관련 추가 잊지 말 것

3. 자바파일 추가하기 

package com.soft.websocket;

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

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Test_webSocketHandler extends TextWebSocketHandler {

    private final List<WebSocketSession> sessions = new ArrayList<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public Test_webSocketHandler() {
        startMessageSender();
    }

    private void startMessageSender() {
        scheduler.scheduleAtFixedRate(() -> {
            String currentTime = LocalDateTime.now().format(formatter);
            String message = "서버 시간: " + currentTime;

            synchronized (sessions) {
                for (WebSocketSession session : sessions) {
                    if (session.isOpen()) {
                        try {
                            session.sendMessage(new TextMessage("서버에서 보내는 10초마다의 메시지: " + message));
                        } catch (Exception e) {
                            System.err.println("메시지 전송 오류: " + e.getMessage());
                        }
                    }
                }
            }
        }, 0, 3, TimeUnit.SECONDS);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        synchronized (sessions) {
            sessions.add(session);
        }
        System.out.println("새로운 WebSocket 연결: " + session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("수신된 메시지: " + payload);
        /*
        synchronized (sessions) {
            for (WebSocketSession webSocketSession : sessions) {
                if (webSocketSession.isOpen()) {
                    webSocketSession.sendMessage(new TextMessage("서버로부터의 응답: " + payload));
                }
            }
        }
        */
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        synchronized (sessions) {
            sessions.remove(session);
        }
        System.out.println("WebSocket 연결 종료: " + session.getId());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.err.println("WebSocket 오류: " + exception.getMessage());
    }

    public void destroy() {
        scheduler.shutdown();
        try {
            if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
                scheduler.shutdownNow();
            }
        } catch (InterruptedException e) {
            scheduler.shutdownNow();
        }
    }
}

4. JSP파일에서 자바스크립트로 호출해서 연결 잘되었는지 확인하기 

<script>
	const host = window.location.host;  // 현재 웹 페이지의 호스트 정보 가져오기
	const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://'; // 현재 페이지가 HTTPS라면 wss 사용, 아니면 ws 사용
	const socket = new WebSocket(`${protocol}${host}/testwebsockethandler01`);
	//const socket = new WebSocket('ws://localhost:8080/jspculturedepot/testwebsockethandler01');
	const browserInfo = navigator.userAgent;
	socket.onopen = function() {
	    console.log('웹소켓 연결이 열렸습니다.');
	    socket.send('안녕하세요 서버!');
	    socket.send('나의정보 브라우저정보 : '+browserInfo);
	};
	
	socket.onmessage = function(event) {
	    console.log('서버로부터 메시지:', event.data);
	    //alert('서버로부터 받은 메시지: ' + event.data); // 메시지를 alert 창으로 띄우기
	    socket.send('잘받은 브라우저정보 : '+browserInfo);
	};
	
	socket.onclose = function() {
	    console.log('웹소켓 연결이 닫혔습니다.');
	};
	
	socket.onerror = function(error) {
	    console.error('웹소켓 오류:', error);
};
</script>

호출 주소를 보면 알겠지만 XML에 추가한 

<websocket:handlers>
        <websocket:mapping path="/testwebsockethandler01" handler="WebSocketHandler01"/>
    </websocket:handlers>

이 부분이 PATH로 호출합니다.

블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,