reactjsspring-bootwebsocketspring-websocket

How to properly configure websocket with springboot and reactjs?


I can establish a websocket connection with my springboot server but I can't access the endpoint from @MessageMapping when I'm trying to send a message. Here are my configurations:

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/simulator")
            .setAllowedOrigins("http://myiphere:3000")
            .withSockJS();
}

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

And a simple controller :

@RestController
@RequestMapping("/api")
public class MyController {

 @MessageMapping("/hello/")
 @SendTo("/endpoint/greeting")
 public Greeting getCurrentLocation() {
     System.out.println("hello here");
     return GenericBuilder.of(Greeting::new)
                          .with(Greeting::setContent, "hello from server")
                          .build();
 }

}

I'm using the socketjs-client library in ReactJS by following this tutorial :

import SockJS from "sockjs-client";
import Stomp from "stompjs";

let stompClient;

const connect = () => {
    const socket = new SockJS("http://myiphere:8081/simulator");
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log("Connected " + frame);
        stompClient.subscribe("http://myiphere:8081/endpoint/greeting", function (greeting) {
        console.log("hi" + JSON.parse(greeting.body).content);
        });
    });
};

const sendSomething = () => {
    stompClient.send("http://myiphere:8081/app/hello/", {});
};

And some buttons with onClick events bound to the methods above. The connection is working, I'm getting "connected" messages in browser console but when I'm trying to click the button with sendSomething() I'm not getting anything in the browser's console nor server's console.


Solution

  • Solved.

    The problem was the absolute url path in the send() method.

    P.S.: And I've been looking for an answer for this problem on many sites and found out that there is no need to use absolute path for subscribe() url.

    P.P.S.: In case that someone else have these problems, look for extra / too. You have to be careful when you're setting the url. The pattern from JS should match the one from SpringBoot.