Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 4 websockets dynamic MessageMapping not executed

I'm using Spring 4 websockets on Tomcat 8 and I have the following configuration:

<websocket:message-broker application-destination-prefix="/app">
    <websocket:stomp-endpoint path="/notify">
        <websocket:sockjs />
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic" />
</websocket:message-broker>

My Spring controller has the following method:

@MessageMapping("/notify/{client}")
public void pushMessage(@DestinationVariable long client, String message) {
    System.out.println("Send " + message + " to " + client);
    template.convertAndSend("/topic/push/" + client, message);
}

So what I'm trying to do here is that if client 1 wants to send a message to client 2, he uses /app/notify/2. The Spring controller will then push the message to topic /topic/push/2.

I wrote the following code in my client:

var id = 1;
var sock = new SockJS('/project/notify');
var client = Stomp.over(sock);
client.connect({}, function() {
    client.subscribe('/topic/push/' + id, function(message) {
        console.log(message);
    });
});

The connection works perfectly, /project is just the context root of my application.

I also have the following code in my client to send a message:

client.send('/app/notify/' + id, {}, "test");

Both variables (client and id) are accessible, I'm not getting any errors from this part of the code and I can see in my console that the message is actually sent:

>>> SEND
destination:/app/notify/1
content-length:4

test 

However, the System.out.println() statement in my controller is never executed, so I assume there is something wrong with my controller mappings or I'm not using the destination endpoints correctly (I don't understand why I have to specify the application prefix here, but not when connecting to that endpoint).

like image 219
g00glen00b Avatar asked Oct 02 '22 09:10

g00glen00b


1 Answers

It seems it's unable to map when using a simple String message as payload. When I wrap the message in an object, then it works just fine.

EDIT: As stated in the comments, Spring already comes with a message wrapper called the TextMessage class.

like image 106
g00glen00b Avatar answered Oct 05 '22 10:10

g00glen00b