javaspringspring-bootsocketsspring-websocket

Unable to hit the websocket endpoint from frontend


I am writing have configured websocket endpoint using below given code at backend part. And I created a endpoint in controller. Now I am hitting the url from front end but the controller method is not invoked.

WebSocketConfig.java


package com.learn.example.demo.Configs;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/stomp-endpoint")
                .setAllowedOriginPatterns("*");
//                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // to send message - hit /app/url endpoint
        // to subscribe - hit topic/url
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Bean
    public CustomWebSocketHandler customWebSocketHandler(){
        return new CustomWebSocketHandler();
    }


    @Bean
    public DefaultHandshakeHandler handshakeHandler() {
        return new DefaultHandshakeHandler();
    }
}

Endpoint which I created is :


 @MessageMapping("/app/sendMessage/{id}/{chatId}")
    @SendTo("/topic/chat/{chatId}")
    public Chat saveMessage(@RequestHeader("auth-token") String authToken, @PathVariable String chatId, @PathVariable String id, @RequestBody Chat chat){
        return sendMessage(authToken, chatId, id, chat);
    }

    public Chat sendMessage(String authToken, String chatId, String id, Chat chat) {
        System.out.println("Hello");
        return service.saveChat(authToken, chat, id, chatId);
    }

From front end I am calling the backend and connected is coming but this endpoint is not hit

const configureStompEndpoint = async () => {
    const stomp = new Client();

    await stomp.configure({
      brokerURL: 'ws://localhost:3030/stomp-endpoint',
      debug: (str) => {
        console.log(str);
      },
      reconnectDelay: 5000,
      heartbeatIncoming: 4000,
      heartbeatOutgoing: 4000,
    });

    // Use a Promise to wait for the STOMP connection to be established
    const connectPromise = new Promise((resolve) => {
      stomp.onConnect = () => {
        console.log('Connected to WebSocket');
        resolve();
      };
    });

    try {
      // Connect to the WebSocket server
      stomp.activate();
    } catch (error) {
      console.error('Error connecting to WebSocket:', error);
    }

    // Wait for the STOMP connection to be established
    await connectPromise;

    // Subscribe to the STOMP destination
    const subscription = stomp.subscribe(``, (message) => {
      const chat = JSON.parse(message.body);
      // Handle incoming messages
      setPreviousMessages((prevMessage) => [...prevMessage, chat]);
    });

    // Save the STOMP client and subscription in state
    setStompClient(stomp);

    // Clean up the subscription on component unmount
    return () => {
      console.log('Unsubscribing from WebSocket');
      subscription.unsubscribe();
    };
  };

Please help me solve this problem!


Solution

  • Spring boot automatically detects the /app/send enpoint so instead of hitting /app/send hit /send endpoint and it will work.