Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Stomp Headers using Spring websockets

I have a basic spring websocket application which currently sends basic data to subscribers. Currently the system uses the SimpMessageSendingOperations class as the message handler. If I call SimpMessageSendingOperations.convertAndSend(destination, object) then the object is converted and received by the subscribed clients.

I would like to be able to send a custom header to the clients. I have tried using the SimpMessageSendingOperations.convertAndSend(destination, object, headers) method to do this. However the custom header is not included in the stomp message.

Debugging through the code it looks like StompHeaderAccessor.toStompHeaderMap() method calls toNativeHeaderMap() which uses the native header and the original native header maps to build up the stomp headers.

Is there a way to get a custom header added to stomp message?

like image 588
Jaimie Whiteside Avatar asked Jan 31 '14 12:01

Jaimie Whiteside


1 Answers

StompHeaderAccessor extends NativeMessageHeaderAccessor which seems to be where the non-stomp headers live, except they are all stored in a single header called nativeHeaders - which itself is a map.

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public  GenericMessage<Greeting> greeting(HelloMessage message) throws Exception {      
    Map<String, List<String>> nativeHeaders = new HashMap<>();
    nativeHeaders.put("hello", Collections.singletonList("world"));

    Map<String,Object> headers = new HashMap<>();
    headers.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, nativeHeaders);

    return new GenericMessage<Greeting>(new Greeting("Hello, " + message.getName() + "!"), headers);
}

A simple interceptor server-side to wrap your custom headers to the nativeHeaders header should be enough to expose them client-side where they would be available as a map message.headers.nativeHeaders. Simmilarly, you could write a client-side interceptor to move the nativeHeaders into the regular headers - so before your client is aware of the message, all the expected headers are simply in the message.headers.

like image 102
Paul Adamson Avatar answered Sep 27 '22 19:09

Paul Adamson