상세 컨텐츠

본문 제목

Spring boot WebSocket(스프링 부트 웹소켓 사용)

스프링부트

by e7e 2024. 11. 11. 23:34

본문

작성 중..... 

 

application.properties

logging.level.com.e7e.socket=debug

 

 

 

SampleWebSocketConfig.java

package com.e7e.socket.sample;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@EnableWebSocket
public class SampleWebSocketConfig implements WebSocketConfigurer  {

	@Autowired
	private SampleSocketIntercepter sampleSocketIntercepter;
	
	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		
		log.debug("체킁");
		registry
		.addHandler(webSocketHandler(), "/chat")
		.setAllowedOriginPatterns("*")
		.addInterceptors(sampleSocketIntercepter);
		
	}

	
	@Bean
	protected WebSocketHandler webSocketHandler() {
		log.debug("체로롱");
		return new SampleWebSocketHandler();
	}

}

 

 

SampleWebSocketHandler.java

package com.e7e.socket.sample;

import java.util.ArrayList;
import java.util.List;

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;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SampleWebSocketHandler extends TextWebSocketHandler {

	private static List<WebSocketSession> list = new ArrayList<WebSocketSession>();
	
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		log.info("## 누군가 접속");
		list.add(session);
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		//String uMsg = message.getPayload();
		for (WebSocketSession webSocketSession : list) {
			webSocketSession.sendMessage(message);
		}
	}
	
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		log.info("## 누군가 떠남");
		list.remove(session);
	}

}

 

 

SampleSocketIntercepter.java

package com.e7e.socket.sample;

import java.util.Enumeration;
import java.util.Map;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

@Component
public class SampleSocketIntercepter implements HandshakeInterceptor {

	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {


		HttpServletRequest req = ((ServletServerHttpRequest)request).getServletRequest();
		HttpSession session  =  req.getSession(false);
	
		// HttpSession에 머가 들어있다면 담장
		if(session != null) {
			
			Enumeration<String> attNames = session.getAttributeNames();

			while(attNames.hasMoreElements()) {
				String attName = attNames.nextElement();
				Object attValue = session.getAttribute(attName); 				
				attributes.put(attName,attValue);
			}					
		}
		// 그냥 계속 진행
		return  true;  
		
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception exception) {
		// 지금은 할 일이 생각 안남
		
	}


}

 

 

index.html

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>E7E 체킁</title>
	<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
	<style>
		* {
			box-sizing: border-box;
		}

		#wrapper {
			width: 60vw;
			margin: 10px auto;
			text-align: center;
		}

		#e7eChat {
			min-height: 450px;
			border: 1px groove pink;
		}

		#e7eTitle {
			background-color: black;
			color: yellowgreen;
		}

		#e7eConn {
			margin-top: 10px;
		}

		#e7eInput {
			width: 100%;
			height: 50px;
			border: 10px groove gold;
			text-align: center;
			display: none;
		}
	</style>
</head>

<body>
	<div id="wrapper">
		<h1 id="e7eTitle">E7E와 아무말 대잔치</h1>
		<div id="e7eChat">
		</div>
		<div id="e7eConn">
			아이디: <input type="text" id="chatId" autofocus value="">
			<button onclick="suminConn()">연결할꼬얌</button>
		</div>
		<div id="e7eInput" contenteditable tabindex="0" onkeydown="suminEnter(this)">
		</div>
	</div>
	<script>
		// 고정 element(요소)
		const e7eChat = document.querySelector("#e7eChat");
		const e7eConn = document.querySelector("#e7eConn");
		const chatId = document.querySelector("#chatId");
		const e7eInput = document.querySelector("#e7eInput");
		// 전역 변수	
		let webSocket = null;
		let hostport = location.href.split("/")[2];
		
		// 전역 함수
		function suminEnter(cont) {
			if (event.keyCode == 13) {
				event.preventDefault(); // 요거이 있어야 <br> 2개 안 들어감.

				let myDiv = document.createElement("div");
				myDiv.style.textAlign = "right";
				myDiv.innerHTML = cont.innerHTML;

				e7eChat.appendChild(myDiv);
				cont.innerHTML = "";
			}
		}

		function suminConn() {
			webSocket = new WebSocket(`ws://${hostport}/chat`);

			// 웹소켓  이벤트 
			webSocket.onopen = () => {
				console.log("E7E 연결 되었쪙");
				webSocket.send("안농")
			}

			webSocket.onmessage = () => {
				console.log("체킁", event.data)
			}

			webSocket.onclose = () => {
				console.log("닫혔어요")
			}

			webSocket.onerror = () => {
				console.log("에러가 났나봐요")
			}
		}

	</script>
</body>

</html>

 

 

스프링으로 하는 건 아래  글 참조....

 

2022.04.28 - [스프링] - 초간단 WebSocket 채팅

 

 


 

부는 바람에 일말의 저항감도 없이 그저 떨어지는 낙엽처럼

난 메롱 메롱 Crazy 상태 , 

 

내 의지, 체력 머 그딴 내 안에 있던 그들은 지금 바닥에서 나뒹글다  

 

Crazy

 

https://www.youtube.com/watch?v=n6B5gQXlB-0

 

'스프링부트' 카테고리의 다른 글

sts4 spring boot 세번쨍  (0) 2023.07.10
sts4 spring boot 두번쨍  (0) 2023.07.04
sts4 spring boot 첫번쨍  (0) 2023.07.03

관련글 더보기