[Tistory] [ws] Spring 에서 Websocket 연결하기

원글 페이지 : 바로가기

Latency alone is not a deciding factor. If the volume of messages is relatively low (e.g. monitoring network failures) HTTP streaming or polling may provide an effective solution. It is the combination of low latency, high frequency and high volume that make the best case for the use WebSocket. https://docs.spring.io/spring-framework/docs/5.0.4.RELEASE/spring-framework-reference/web.html#websocket-intro-when-to-use Web on Servlet Stack This part of the reference documentation covers support for Servlet stack, WebSocket messaging that includes raw WebSocket interactions, WebSocket emulation via SockJS, and pub-sub messaging via STOMP as a sub-protocol over WebSocket. 4.1. Introduction The docs.spring.io 먼저 클라이언트가 서버에 HTTP 프로토콜로 핸드쉐이크 요청을 한다. 서버에서는 응답 코드를 101 로 응답해준다. 웹소켓을 위한 포트 HTTP 또는 HTTPS 통신을 위해 오픈한 포트를 사용한다. 웹소켓은 HTTP 포트 80, 와 HTTPS 443위에서 동작되도록 설계가 되었다. 별도의 포트를 오픈할 필요가 없다. 호환을 위해서 핸드쉐이크는 HTTP upgrade 헤더를 사용하며, HTTP 프로토콜에서 웹소켓 프로토콜로 변경한다. ws와 wws의 차이 : 우리는 보안을 위해서 HTTP 가 아닌 HTTPS를 사용하듯 웹소켓도 wss로 통신해야 시큐어 통신이 가능하다. 스프링부트에서 웹소켓을 연동하는 방법 Spring Framework 공식문서를 참조하였다. 1. build.gradle 에 의존성 추가 dependencies {
implementation ‘org.springframework.boot:spring-boot-starter-web’
implementation ‘org.springframework.boot:spring-boot-starter-websocket’
implementation ‘org.springframework.boot:spring-boot-starter’
} 2. WebSocketConfigurer 인터페이스를 구현한 WebSocketConfiguration 클래스 작성 //WebSocketConfig.java
package com.patientpal.backend.config;

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;

@Configuration
//enableWebsocket 으로 웹소켓 서버를 사용하도록 정의
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), “/myHandler”);
}

//MyHandler클래스를 웹소켓 핸들러로 정의
@Bean
public WebSocketHandler myHandler() {
return new MyHandler();
}

} 3. 웹소켓 핸들러 클래스 작성 웹소켓 핸들러 클래스는 4개의 메서드를 오버라이드 해야한다. afterConnectionEstablished handleTextMessage afterConnectionClosed handleTransportError //MyHandler.java
package com.patientpal.backend.config;

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 MyHandler extends TextWebSocketHandler {
//최초 연결 시 call
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {

}

//양방향 데이터 통신할 때 call
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//do something
}

//웹소켓 종료시 call
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

}

//통신 에러 발생 시 call
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

}

} Postman으로 connection 을 시도하면 연결이 잘 된 것을 확인할 수 있다. Request URL: http://localhost:8080/myHandler 이라고 뜨는데, http 가 아닌 ws 프로토콜을 이용하는데 왜 http로 뜰까? 라고 생각했다. 하지만 거듭 생각해보니 request는 http 로 시작하되, 은밀하게 upgrade요청을 보내야 ws로 upgrade 된다는 코딩애플 님의 말이 생각나서! 갑자기 깨달았다 아래 response 부분에 보면 Upgrade=”websocket”으로 적혀있는 것을 볼 수 있다. ref : https://supawer0728.github.io/2018/03/30/spring-websocket/ Spring WebSocket 소개 서론Web Browser에서 Request를 보내면 Server는 Response를 준다. HTTP 통신의 기본적인 동작 방식이다. 하지만 Server에서 Client로 특정 동작을 알려야 하는 상황도 있다. 예를 들어 Browser로 Facebook에 접속해 supawer0728.github.io https://brunch.co.kr/@springboot/801 Spring WebSocket Ping/Pong 설연휴를 (허무하게) 보내는게 아쉬워서, 연휴 마지막날 짧은 글을 작성해서 공유한다. 주제는, Spring WebSocket Ping/Pong 이다. ping/pong 이 왜 필요하고, ping/pong 구현 방법에 대해서 간단하게 소개하 brunch.co.kr https://docs.spring.io/spring-framework/reference/web/websocket/server.html WebSocket API :: Spring Framework The Spring WebSocket API is easy to integrate into a Spring MVC application where the DispatcherServlet serves both HTTP WebSocket handshake and other HTTP requests. It is also easy to integrate into other HTTP processing scenarios by invoking WebSocketHtt docs.spring.io https://docs.spring.io/spring-session/reference/guides/boot-websocket.html Spring Session – WebSocket :: Spring Session In a typical Spring WebSocket application, you would implement WebSocketMessageBrokerConfigurer. For example, the configuration might look something like the following: @Configuration @EnableScheduling @EnableWebSocketMessageBroker public class WebSocketCo docs.spring.io https://velog.io/@xxx-sj/spring%EC%9B%B9%EC%86%8C%EC%BC%93%EC%9C%BC%EB%A1%9C-%EC%B1%84%ED%8C%85-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-2-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8-%EC%83%9D%EC%84%B1-%EB%B0%8F-%EC%8A%A4%ED%94%84%EB%A7%81%EC%9B%B9%EC%86%8C%EC%BC%93 [spring-vue]웹소켓으로 채팅 구현하기 (2) – 프로젝트 생성 및 스프링웹소켓 웹소켓으로 채팅 구현하기 velog.io https://brunch.co.kr/@springboot/695

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다