Ajax, WebSocket ?
Ajax | WebSocket |
서버와 클라이언트 간의 통신. | |
단방향 통신 (Client -> Server) | 양방향 통신 ("Client -> Server" / "Server ->Client") |
SpringFramework --> ws protocol 사용 SpringBoot --> stomp protocol 사용 |
"SpringBoot" 기반으로 웹소켓 연습.
WebSocket Exercise..
1. pom.xml 수정 (의존성 추가)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> |
2. WebSocketConfig 설정 파일생성
import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker //EnableWebSocketMessageBroker is used to enable our WebSocket server public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.setApplicationDestinationPrefixes("/app"); registry.enableSimpleBroker("/topic"); } } |
org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer인터페이스 구현 @Configuration - 해당 클래스가 Bean의 설정을 할 것을 표현하는 어노테이션 (Bean 수동등록) @EnableWebSocketMessageBroker - "WebSocket Server" 활성화하는데 사용. configureMessageBroker Method - 한 클라이언트에서 다른 클라이언트로 메시지를 라우팅 하는 데 사용될 메시지 브로커 구성. registry.setApplicationDestinationPrefixes("/app"); - "/app" 시작되는 메시지가 message-handling methods으로 라우팅 되어야 한다는 것을 명시. registry.enableSimpleBroker("/topic"); - "/topic" 시작되는 메시지가 메시지 브로커로 라우팅 되도록 정의. 메시지 브로커는 특정 주제를 구독 한 연결된 모든 클라이언트에게 메시지를 broadcast 한다. |
3. ChatController 생성 (Config 설정파일과 매핑되어 라우팅 담당)
@Controller public class ChatController { @MessageMapping("/chat.sendMessage") @SendTo("/topic/public") public ChatMessage sendMessage(@Payload ChatMessage chatMessage) { return chatMessage; } @MessageMapping("/chat.addUser") @SendTo("/topic/public") public ChatMessage addUser(@Payload ChatMessage chatMessage , SimpMessageHeaderAccessor headerAccessor){ headerAccessor.getSessionAttributes().put("username", chatMessage.getSender()); return chatMessage; } @RequestMapping("/chat") public String goChat() { return "index.jsp"; } } |
작성중..
'BackEnd_Servers' 카테고리의 다른 글
[BackEnd_Servers] JAVA8(Stream API) 이해 및 활용(1) (0) | 2021.10.19 |
---|---|
[BackEnd_Servers] JAVA8(Optional Class) 정의 및 활용 (0) | 2021.10.13 |
@RequestBody, @ModelAttribute, @RequestParam (0) | 2021.10.08 |
[BackEnd_Servers] REST API (GET/POST/PUT/DELETE) (0) | 2021.10.04 |