I have a spring application that needs to receive messages using a websocket.
Config.java
@Configuration
@EnableWebSocketMessageBroker
public class Config implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/simulator").setAllowedOrigins("http://localhost:3000").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/endpoint");
registry.setApplicationDestinationPrefixes("/app");
}
}
MessageController.java
@Controller
public class MessageController {
@MessageMapping("/hello")
@SendTo("/endpoint/greeting")
public ResponseEntity<?> getContent(@RequestBody Message message) {
JsonObject jo = new JsonObject();
jo.put("isLiked", "Yes");
System.out.println("here");
System.out.println(message.getName());
return new ResponseEntity<>(jo, HttpStatus.BAD_REQUEST);
}
}
Message.java
public class Message {
private String name;
public Message(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I also have a simple React.js app that has two buttons "connct" and "send". When you click on "connect", a connection with Spring is made and it is successful (I get data in the console about a successful connection). But when I click on "send", I get information that json has been sent, but Spring does not register it in any way (neither displays messages to the console, nor sends a response, nor enters data into the "endpoint/greeting" channel)
App.js
import './index.css';
import SockJS from "sockjs-client"
import Stomp from 'stompjs'
import React, { useState, useRef, useEffect, useCallback } from "react";
function App() {
let stompClient;
const connect = () => {
const socket = new SockJS("http://localhost:8080/simulator");
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log("Connected " + frame);
stompClient.subscribe("http://localhost:8080/endpoint/greeting", function (greeting) {
console.log("hi" + JSON.parse(greeting.body).content);
});
});
};
const sendSomething = () => {
stompClient.send("http://localhost:8080/hello",{}, JSON.stringify({"name":"John"}));
};
return (
<>
<button onClick={connect}>Connect</button>
<button onClick={sendSomething}>Send</button>
</>
);
}
export default App;
I've been having this problem for a few days now. But I still can't find the answer What am I doing wrong?