Issues with Stomp.subscribe functionality in Spring WebSockets

Recently, I've been working on setting up a basic Spring WebSockets application by following the official Spring guide. The main files that I have created for this project are:

WebSocketConfig.java

@ Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

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

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry.addEndpoint("/ws-connect").setAllowedOrigins("*").withSockJS();
    }
}

MessageController.java

@ Controller
public class MessageController {

    @MessageMapping(value = "/test")
    @SendTo("/private")
    public Message message(String messageText) {
        Message message = new Message();
        message.setMessage(messageText);r);
        message.setTimestamp(new Date());
        return message;
    }
}

sockets.js

var stompClient = null;

function connect() {
    var socket = new SockJS('http://localhost:8080/ws-connect');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function(frame) {
        console.log('Connected: ' + frame);
        stompClient.subscribe('/chat/private', function(message) {
            console.log('Here');
            console.log('Message is: ' + message);
        });
        console.log('Here2');
    })
}

connect();

function sendMessage() {
    stompClient.send('/message/test', {}, "Hello self!");;
}

In my index.html file, there is a button that triggers the sendMessage function when clicked. Although the console confirms that the message has been sent, I am not receiving any replies in the subscribe function. Despite successfully connecting to the WebSocket server and logging the expected output, I'm puzzled as to what mistake I might have made. Can anyone pinpoint where I may have gone wrong?

Answer №1

Update /private to /chat/private

Here's how you can make the change :

@Controller
public class MessageController {

    @MessageMapping(value = "/test")
    @SendTo("/chat/private")
    public Message message(String messageText) {
        Message message = new Message();
        message.setMessage(messageText);
        message.setTimestamp(new Date());
        return message;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimal utilization of JSON in JavaScript API: Enhancing Performance, Reinforcing Maintainability, and Optimizing Resources

Currently, I am working on developing an application using Laravel and VueJS (along with Vuex). Although I do not have much experience in working with these frameworks or front-ends, I am curious to know the best practices for utilizing the data received f ...

What could be causing the lack of data to be returned by jQuery.getJSON?

I've come across this method: function getUserName(guid) { var name = "Unknown"; $.getJSON(urlCurrent, { "method" : "get_user_info", "guid" : guid, "auth_token" : temporaryAuthToken }, function(data) { if ...

Pictures are not showing up in the gallery after they have been saved

if (action.equals("saveToGallery")) { JSONObject obj = args.getJSONObject(0); String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null; String imageName = obj.has(" ...

Is it possible in Vue.js to create a reactive functionality for a button using a watcher for "v-if" condition?

I have a userlist page with various profiles, including my own. A button is supposed to appear only when viewing my own profile. The issue arises when switching from a different profile to my own (changing the router parameter) - the button should show up ...

Node.js/Express - unable to retrieve client body data on server

I am able to retrieve data from express but I am facing issues when trying to post data to express... client: <html> <button onclick="myFunction()">send</button> <script> const data = {"experience" : 0}; ...

What is the best way to define objects containing arrays of objects in JavaScript?

I am seeking to create a blueprint for the following data structure, with all values provided by the user: { "name":"ABC", "city":"X", "child": [{"name":"ccc","age":"22"}, {"name":"ccc","age":"22"} ] } This data structure consists of a parent obje ...

Pixels range

Is it possible to create a Range from a given rectangle of pixels, similar to how we can get the bounding rectangle of a Range using getBoundingClientRect? ...

How can I create a jumping animation effect for my <li> element in JQuery?

I have a horizontal navigation bar with a "JOIN" option. My goal is to make the #jump item continuously jump up and down after the page has finished loading. Currently, I have this code which only triggers the jump effect once when hovering over the eleme ...

AngularJS Toggle Directive tutorial: Building a toggle directive in Angular

I'm attempting to achieve a similar effect as demonstrated in this Stack Overflow post, but within the context of AngularJS. The goal is to trigger a 180-degree rotation animation on a button when it's clicked – counterclockwise if active and c ...

The dropdown feature is malfunctioning. (Using Angular 8 and Bootstrap)

I'm encountering an issue with displaying a dropdown and its options using the bootstrap directive 'ngbDropdown'. When I follow this example from the documentation: <div ngbDropdown class="d-inline-block"> <button class="btn ...

What is the process for utilizing JavaScript to parse a JSON file stored locally?

I am trying to retrieve data from a JSON file located locally using JS/jQuery. Despite finding numerous similar questions on Stack Overflow, I have not found the right solution. All answers seem to give me a jquery.min.js:4 XMLHttpRequest cannot load file ...

Why am I unable to utilize methods in Vue.js?

Hey everyone, I'm currently working on a website that includes a home page and a specific 'Brazil' component. To switch between the two, I am using vue router. Within the Brazil component, there is a calculator feature that should take a gra ...

The dynamic duo of MongoDB and Prisma: forging a groundbreaking one-to-many relationship

Is it possible to establish a one-way m-to-n relationship without requiring both collections to have each other's ids? I am attempting the following: model Country { id String @id @default(auto()) @map("_id") @db.ObjectId ...

Step-by-step guide to accessing the detail view upon selecting a table row in react.js

In my project, I have a table with multiple rows. When a row is selected, I want to display detailed information about that particular item. To achieve this functionality, I am utilizing react-router-dom v6 and MUI's material table component. Here is ...

The update depth has reached its maximum limit after attempting to setState upon the user's click action

Having trouble setting state when a user clicks on a list? I have a loop that generates a list of items in li tags, and I want to update the state when a user clicks on one of those li tags. However, React is throwing an error. The error message reads: " ...

What is the best way to flip cards with the onClick event in JavaScript?

My cards are currently facing down with the code* provided. What steps should I take to flip them face up using onClick functions? Furthermore, how can I store the IDs in an Array and use them to retrieve images from my image collection? HTML <table s ...

jQuery is successfully manipulating pagination on CodeIgniter, however, the link is being updated as well

I've been working on a HTML page called view_closing.php. It includes a table with pagination, and my aim is to ensure that the table can move to another record without refreshing the entire page, all while remaining at the same address: http://localh ...

I need assistance in reading a CSV file that has been uploaded via an HTML form using jQuery. Can you provide guidance on

Currently, I am attempting to utilize jQuery in order to read a CSV file. I have implemented an input tag in HTML for the file, but I am encountering some difficulties when it comes to reading it. Below you can find the code that I have put together: HTML ...

Why are the buttons on my HTML/JavaScript page not functioning properly?

I have been struggling with a code for a 5 image slideshow where the NEXT and PREVIOUS buttons are supposed to take me to the next and previous slides. However, when I press them, nothing happens. Can anyone provide some assistance? I need additional detai ...

Introducing the Vue 3 personalized directive

I have developed a custom tooltip directive that is functioning correctly when using the beforeUpdate hooks, but not working with update hooks. The issue arises when multiple elements are created upon hovering over the h1 element, which triggers mouseover ...