[velog.io/@skyepodium/vue-spring-boot-stomp-%EC%9B%B9%EC%86%8C%EC%BC%93
참고하여 간단하게 정리만 했습니다.]
Vue.js 가 localhost:8080/receive 로 보내고
Springboot 가 localhost:8080/send 받아서 다른 Vue.js 로 보내준다.
[서버]
0. 의존성
# web - 스프링 부트의 MVC 패턴을 사용
# websocket - stomp 가 들어있어서 웹소켓을 사용할 수 있다.
# lombok - 게터,세터, 생성자
1. 구조
메시지 정보를 담는 vo ( 유저 정보 , 내용 )
controller ( 메세지를 받는 컨트롤러 )
config ( 웹소켓 endpoint 설정 , cross origin 해재 )
1- 1 웹소켓이 사용할 데이터형태
[ SocketVo.class ]
- 유저
- 내용
1- 2 컨트롤러
[ SocketController.class ]
@Controller
public class SocketController {
@MessageMapping("/receive") /* 메세지를 받을 컨트롤러 (WebSocket에서 제공) */
@SendTo("/topic/public") /* 구독으로 반환해준다 */
public SocketVO SocketHandler(SocketVo socketVo) {
/* /receive에서 SocketVo(메세지)를 받고
/send로 SocketVo(메세지)를 보냄. */
User 유저 = socketVO.get유저();
String 메세지내용 = socketVO.get메세지();
/* /send 로 보내줄 메세지 생성 */
SocketVo result = new SocketVo(유저, 메세지내용);
return result;
}
}
1- 3 설정파일
[ WebSocektConfig.class ]
@Configuration
@EnableWebSocketMessageBroker //웹소켓 메세지 중재자
public class WebSocektConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config){
config.enableSimpleBroker(" /send "); //클라이언트에서 websocket에 접속(구독)하는 endpoint를 등록
}
@Override
public void registerStompEndPoints(StompEndpointRegistry registry){
registry.addEndpoint("/") //클라이언트에서 websocket에 접속하는 endpoint를 등록
.setAllowedOrigins("*") //CORS허용
.withSockJS(); //브라우져에서 websocket을 지원하지 않을 경우 fallback 옵션을 활성화
}
}
[클라이언트]
0. 의존성
# sockjs-client - 웹소켓 객체를 생성
# webstomp-client - stomp를 사용
1. 필요한 컴포넌트
# 소켓 연결
methods : {
connect(event){
var socket = new Socket("/"); //socket 을 만든다.
stompClient = Stomp.over(socket); //websocket을 연결 합니다.
stompClient.connect({}, onConnected, onError); //websocket 을 연결합니다. 그리고, onConnected로 보내줍니다.
}
Connect(){
const serverURL = "http://localhost:8080"
let socket = new SockJS(serverURL); //소켓을위한 서버주소 셋팅
this.stompClient = Stomp.over(socket); //Stomp에 소켓 등록
this.stompClient.connect( //등록된 소켓으로 실제로 연결
{},frame => {
this.stompClient.subscribe("/send",
res => { console.log('구독으로 받은 메시지', res.body);
});
}
}
# 메세지 전송
methods:{
send() {
if (this.stompClient && this.stompClient.connected) {
const msg = {
userName: this.userName,
content: this.message
};
this.stompClient.send("/receive", JSON.stringify(msg), {});
}
},
}
# 메세지 수신
'Spring' 카테고리의 다른 글
Springboot 페이징처리 Parameter 에러 (0) | 2021.05.25 |
---|---|
pub sub 구조 ( 웹소켓 채팅 ) (0) | 2021.05.08 |
Business Exception 처리 (0) | 2021.04.29 |
Exception Guide 예외처리 방법 [Spring] (0) | 2021.04.29 |
SpringSecurity 설정후 Post 요청 불가능 ( 403에러 ) 해결 (1) | 2021.04.16 |