0

I am working on a Spring Boot application using WebSocket for real-time user-specific notifications. Although the WebSocket connection is established and notifications are correctly sent from the server, they are not being received by the client. Here are the details of my setup:

Configuration and Code: WebSocketConfig:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket").setAllowedOrigins("*");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }
}
@RestController
public class MessageController {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @RequestMapping("/sendMessage")
    public void sendMessage() {
        String message = "Hello from the server!";
        messagingTemplate.convertAndSend("/topic/messages", message);
    }

    @MessageMapping("/hello")
    @SendTo("/topic/messages")
    public String handleMessage(String message) {
        System.out.println("Received message: " + message);
        return "Server response: " + message;
    }
}

test:

@SpringBootTest
public class WebSocketTestBackend {

    private static final String URL = "ws://localhost:8080/websocket";

    @Test
    public void testWebSocketConnection() throws InterruptedException, ExecutionException {
        List<Transport> transports = new ArrayList<>(2);
        transports.add(new WebSocketTransport(new StandardWebSocketClient()));
        SockJsClient sockJsClient = new SockJsClient(transports);

        WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);

        StompSessionHandlerAdapter stompSessionHandler = new StompSessionHandlerAdapter() {
            @Override
            public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
                System.out.println("Connected to WebSocket server!");
                System.out.println("Connected headers: " + connectedHeaders);
            }



            @Override
            public void handleTransportError(StompSession session, Throwable exception) {
                System.err.println("Transport error occurred: " + exception.getMessage());
            }

            @Override
            public Type getPayloadType(StompHeaders headers) {
                return String.class;
            }

            @Override
            public void handleFrame(StompHeaders headers, Object payload) {
                System.out.println("Received message: " + payload);
                System.out.println("Message headers: " + headers);
            }
        };

        System.out.println("Connecting to WebSocket server...");
        StompSession stompSession = stompClient.connect(URL, stompSessionHandler).get();
        System.out.println("Connected to WebSocket server");

        System.out.println("Subscribing to /topic/messages...");
        stompSession.subscribe("/topic/messages", new StompFrameHandler() {
            @Override
            public Type getPayloadType(StompHeaders headers) {
                return String.class;
            }

            @Override
            public void handleFrame(StompHeaders headers, Object payload) {
                System.out.println("Received message: " + payload);
                System.out.println("Message headers: " + headers);
            }
        });
        System.out.println("Subscribed to /topic/messages");

        System.out.println("Sending message to /app/hello...");
        stompSession.send("/app/hello", "Hello, World!".getBytes());
        System.out.println("Message sent to /app/hello");

        Thread.sleep(5000); // Attendre pour recevoir les messages

        stompSession.disconnect();
        System.out.println("Disconnected from WebSocket server.");
    }
}

I Did sent a message but what im expecting is to receive the message in my console here's my logs:


2024-06-19T11:53:19.108+01:00  INFO 972 --- [demo2] [           main] com.example.demo.Demo2Application        : Starting Demo2Application using Java 21.0.2 with PID 972 (C:\Users\User Ob\Documents\ManagementSystemV2\demo\demo2\target\classes started by Hamza Afroukh in C:\Users\User Ob\Documents\ManagementSystemV2\demo\demo2)
2024-06-19T11:53:19.112+01:00  INFO 972 --- [demo2] [           main] com.example.demo.Demo2Application        : No active profile set, falling back to 1 default profile: "default"
2024-06-19T11:53:20.746+01:00  INFO 972 --- [demo2] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2024-06-19T11:53:20.765+01:00  INFO 972 --- [demo2] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2024-06-19T11:53:20.765+01:00  INFO 972 --- [demo2] [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.24]
2024-06-19T11:53:20.837+01:00  INFO 972 --- [demo2] [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2024-06-19T11:53:20.838+01:00  INFO 972 --- [demo2] [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1662 ms
2024-06-19T11:53:21.135+01:00 TRACE 972 --- [demo2] [           main] o.s.w.s.s.s.WebSocketHandlerMapping      : Mapped [/websocket] onto org.springframework.web.socket.server.support.WebSocketHttpRequestHandler@3f183caa
2024-06-19T11:53:21.135+01:00 DEBUG 972 --- [demo2] [           main] o.s.w.s.s.s.WebSocketHandlerMapping      : Patterns [/websocket] in 'stompWebSocketHandlerMapping'
2024-06-19T11:53:21.206+01:00 TRACE 972 --- [demo2] [           main] .WebSocketAnnotationMethodMessageHandler : Looking for @MessageExceptionHandler mappings: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4ce1d6d0, started on Wed Jun 19 11:53:19 WEST 2024
2024-06-19T11:53:21.232+01:00 DEBUG 972 --- [demo2] [           main] .WebSocketAnnotationMethodMessageHandler : 
    c.e.d.MessageController:
    {[MESSAGE],[/hello]}: handleMessage(String)
2024-06-19T11:53:21.245+01:00 DEBUG 972 --- [demo2] [           main] .WebSocketAnnotationMethodMessageHandler : 
    o.s.b.a.w.s.e.BasicErrorController:
    
2024-06-19T11:53:21.632+01:00  WARN 972 --- [demo2] [           main] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: fab5a9d6-3e8a-4bea-bfd4-a2f338c7bca2

This generated password is for development use only. Your security configuration must be updated before running your application in production.

2024-06-19T11:53:21.675+01:00  INFO 972 --- [demo2] [           main] r$InitializeUserDetailsManagerConfigurer : Global AuthenticationManager configured with UserDetailsService bean with name inMemoryUserDetailsManager
2024-06-19T11:53:21.823+01:00  INFO 972 --- [demo2] [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter@64b018f3, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@20801cbb, org.springframework.security.web.context.SecurityContextHolderFilter@800d065, org.springframework.security.web.header.HeaderWriterFilter@6dce59e, org.springframework.web.filter.CorsFilter@581b1c08, org.springframework.security.web.csrf.CsrfFilter@4e245739, org.springframework.security.web.authentication.logout.LogoutFilter@483f286e, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@648c5fb3, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@5e593b08, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@1c240cf2, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@4f116ca2, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@38d80d65, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@5a0e0886, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@78b7f805, org.springframework.security.web.access.ExceptionTranslationFilter@3fde8f7c, org.springframework.security.web.access.intercept.AuthorizationFilter@4aeb0e2b]
2024-06-19T11:53:21.925+01:00  INFO 972 --- [demo2] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2024-06-19T11:53:21.927+01:00 DEBUG 972 --- [demo2] [           main] o.s.m.s.ExecutorSubscribableChannel      : clientOutboundChannel added SubProtocolWebSocketHandler[StompSubProtocolHandler[v10.stomp, v11.stomp, v12.stomp]]
2024-06-19T11:53:21.928+01:00 DEBUG 972 --- [demo2] [           main] o.s.m.s.ExecutorSubscribableChannel      : clientInboundChannel added WebSocketAnnotationMethodMessageHandler[prefixes=[/app/]]
2024-06-19T11:53:21.929+01:00  INFO 972 --- [demo2] [           main] o.s.m.s.b.SimpleBrokerMessageHandler     : Starting...
2024-06-19T11:53:21.929+01:00 DEBUG 972 --- [demo2] [           main] o.s.m.s.ExecutorSubscribableChannel      : clientInboundChannel added SimpleBrokerMessageHandler [org.springframework.messaging.simp.broker.DefaultSubscriptionRegistry@3e900e1a]
2024-06-19T11:53:21.929+01:00 DEBUG 972 --- [demo2] [           main] o.s.m.s.ExecutorSubscribableChannel      : brokerChannel added SimpleBrokerMessageHandler [org.springframework.messaging.simp.broker.DefaultSubscriptionRegistry@3e900e1a]
2024-06-19T11:53:21.930+01:00  INFO 972 --- [demo2] [           main] o.s.m.s.b.SimpleBrokerMessageHandler     : BrokerAvailabilityEvent[available=true, SimpleBrokerMessageHandler [org.springframework.messaging.simp.broker.DefaultSubscriptionRegistry@3e900e1a]]
2024-06-19T11:53:21.930+01:00  INFO 972 --- [demo2] [           main] o.s.m.s.b.SimpleBrokerMessageHandler     : Started.
2024-06-19T11:53:21.930+01:00 DEBUG 972 --- [demo2] [           main] o.s.m.s.ExecutorSubscribableChannel      : clientInboundChannel added UserDestinationMessageHandler[DefaultUserDestinationResolver[prefix=/user/]]
2024-06-19T11:53:21.930+01:00 DEBUG 972 --- [demo2] [           main] o.s.m.s.ExecutorSubscribableChannel      : brokerChannel added UserDestinationMessageHandler[DefaultUserDestinationResolver[prefix=/user/]]
2024-06-19T11:53:21.940+01:00  INFO 972 --- [demo2] [           main] com.example.demo.Demo2Application        : Started Demo2Application in 3.441 seconds (process running for 4.146)
2024-06-19T11:54:21.918+01:00  INFO 972 --- [demo2] [MessageBroker-1] o.s.w.s.c.WebSocketMessageBrokerStats    : WebSocketSession[0 current WS(0)-HttpStream(0)-HttpPoll(0), 0 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(0)-CONNECTED(0)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], outboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], sockJsScheduler[pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]

0

Browse other questions tagged or ask your own question.