I'm trying to build a Spring
STOMP websocket + ActiveMQ
service. I have set the websocket and the ActiveMQ queue.
ActiveMQ
queue works just fine but I'm not able to make my websocket endpoint send messages to the clients connected to the topic.
Websocket client seems to connect just fine also. The thing is that when the controller receives information it is not caught on the client.
--WebsocketConfig.java--
@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
}
--WebsocketController.java--
@Controller
public class WebsocketController {
@Autowired
private ItemService itemService;
@JmsListener(destination = "items-queue")
@MessageMapping("/websocket")
@SendTo("/topic/items")
public String itemsWebsocket(Iterable<Item> items) {
System.out.println("Websocket controller reached");
for (Item item : items) System.out.println(item.getName());
return "hi from websocket";
}
}
--app.js--
let stompClient = null;
function connect() {
let socket = new SockJS('/websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/items', function (items) {
appendItems(items);
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
console.log("Disconnected");
}
function appendItems(items) {
console.log(items);
const itemListContainer = document.getElementById("item-list");
itemListContainer.innerText = "";
Array.from(items).forEach( item => {
const itemContainer = document.createElement("div");
itemContainer.innerText = item.name;
itemListContainer.append(itemContainer);
});
}
connect();