본문 바로가기
Spring

스프링부트 프로젝트에 웹소캣 적용 // WebSocket 1대 1채팅(오류 기록)

by aesup 2021. 6. 3.
728x90

웹소캣때매 3일동안 미쳐버리는줄알았다. 팀프로젝트때 나의 담당이 1대1채팅이라 공부를 하며 프젝을 하게 되었는데... sample1.html:51 WebSocket connection to 'ws://localhost:3000/chating' failed: 때매 하루를 통으로 날렸다

처음엔 stomp로 진행을 했는데 stomp랑 websocket config 해줄때 헷갈려서 오류를 발생하게 했다.

 

WebSocketConfig  (WebSocket)

package bit.com.a.WebSocket;


import org.springframework.context.annotation.Configuration;
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 org.springframework.beans.factory.annotation.Autowired;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer{

	@Autowired
	SocketHandler socketHandler = new SocketHandler();
	
	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(socketHandler, "/chating")
		.setAllowedOrigins("http://localhost:8085");
		System.out.println("연결확인");
		
	}
}

WebSocketConfig  (stomp)

 

package bit.com.achat;

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 WebSocketConfig1 implements WebSocketMessageBrokerConfigurer {
	
	
	
	/*
	 1. WebSocket end-point 및 message broker 를 구성하는것이다.
	 
	 @Configuration = 이 어노테이션은 해당 클래스가 Bean 설정을 할것이다라는 것 나타냄
	 @EnableWebSocketMessageBroker = WebSocket 서버를 활성화하는 데 사용됩니다.
	
	Spring frameworkd는 WebSocket 메시지를 처리하는 Client, 
	Server 측 application을 작성하는데
	사용할 수 있는 WebSocket API를 제공하고 있습니다.
	
	*/
	
	  @Override
	    public void registerStompEndpoints(StompEndpointRegistry registry) {
		  registry.addEndpoint("/ws")
            .setAllowedOrigins("http://localhost:8085")
            .withSockJS();
		  System.out.println("contect ws");
	        //registry.addEndpoint("/ws"); // 그냥 websocket 지원
	    }


	    @Override
	    public void configureMessageBroker(MessageBrokerRegistry registry) {
	        registry.setApplicationDestinationPrefixes("/app");
	        registry.enableSimpleBroker("/topic");
	        System.out.println("configureMessageBroker app topic");
	    }
	
}

 

웹소캣 구성을 할때 stomp에서  withSockJS()를 이용시에는 브라우져에서 websocket을 지원하지 않을 경우 fallback 옵션을 활성화 하는데 사용된다. 저것을 제일 위 WebSocketConfig에 썼었는데 그것때매  connection이 안된것이다.

StompEndpointRegistry 를 사용할때만 적용하는 것인지는 잘 모르겠다.. 계속해서 공부해봐야겠다

728x90