notThatSmart
notThatSmart

Reputation: 1

Spring Web Socket Connection Closed

I have been trying to Connect my React Front-end to Spring-Boot back-end with Web Socket, After Following couple tutorials i managed to send message to my react app, but after a restart i couldn't connect anymore.

React-Code

import SockJS from 'sockjs-client';
import { Client } from "@stomp/stompjs";

useEffect(() => {
        try {
            const socket = new SockJS("http://localhost:7911/ws");
            const stompClient = new Client({
                webSocketFactory: () => socket,
                debug: (str) => { console.log(str); },
                onConnect: () => {

                    stompClient.subscribe("/notification/all", (response) => {
                        console.log('Received message:', response.body);
                    });

                },
                onStompError: (e) => {
                    console.log(e);
                },
            });
            stompClient.activate();
            return () => {
                console.log("Deactivate");
                stompClient.deactivate();
            };
        } catch (e) {
            console.log(e)
        }

    }, []);

Java Code

@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }


    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/notification");
    }
}

I am Using SimpMessagingTemplate to Send the Notification.

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    private static final Logger log = LoggerFactory.getLogger(MessagingService.class);


    public void sendNotification(Message message){
        try {
            simpMessagingTemplate.convertAndSend("/notification/all",message.toString());
        }catch (Exception e){
            log.error("Exception Occurred While Sending Message {}",e);
        }
    }

SecurityConfiguration Class:

public SecurityFilterChain mainFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity.httpBasic((basic) -> basic.disable()).csrf((csrf) -> csrf.disable()).authorizeHttpRequests((auth) -> {
                    auth.requestMatchers(AntPathRequestMatcher.antMatcher(SECURED_API_PATTERN)).authenticated();
                    auth.requestMatchers(AntPathRequestMatcher.antMatcher(OPEN_API_PATTERN)).permitAll();
                    auth.requestMatchers(AntPathRequestMatcher.antMatcher("/**")).permitAll();
                    auth.requestMatchers(AntPathRequestMatcher.antMatcher("/ws/**")).permitAll();
    

                })
                .rememberMe(rememberMe -> rememberMe.key(REMEMBER_ME_SECRET)
                        .tokenValiditySeconds(REMEMBER_ME_DURATION)
                        .rememberMeParameter(REMEMBER_ME_PARAMETER))
                .sessionManagement((session)->session.maximumSessions(1).sessionRegistry(sessionRegistry()))
                .formLogin(httpSecurityFormLoginConfigurer -> {
                    httpSecurityFormLoginConfigurer
                            .loginPage(LOGIN_REQUEST_PAGE)
                            .successHandler(authenticationSuccessHandler())
                            .failureHandler(authenticationFailureHandler())
                            .loginProcessingUrl(LOGIN_PROCESSING_URL)
                            .usernameParameter(EMAIL_PARAMETER)
                            .passwordParameter(PASSWORD_PARAMETER)
                            .permitAll();
                }).logout((logout) -> logout.logoutUrl(LOGOUT_URL)
                        .logoutSuccessHandler(logOutSuccessHandler)
                        .deleteCookies(COOKIE_PARAM)
                        .permitAll())
                .build();
    }

url returns : http://localhost:7911/ws

Welcome to SockJS!

This is Console Debug from the Browser

Opening Web Socket... index-Qpo0fazg.js:400:15644
Connection closed to http://localhost:7911/ws index-Qpo0fazg.js:400:15644
STOMP: scheduling reconnection in 5000ms index-Qpo0fazg.js:400:15644
Opening Web Socket...

Its Quite Curious i managed to get response at first and couldn't afterwards. I checked Windows Fire-Wall Setting didn't find any thing odd there.

Upvotes: 0

Views: 25

Answers (0)

Related Questions