6

In Spring Boot (Websockets)

I just saw this example:

messaging.convertAndSendToUser( username, "/queue/notifications",
                       new Notification("You just got mentioned!"));

Where does the guy get a username from? I can't find any mention about where to get that username...

3
  • The username is the the value that the users provide when they connect to your websocket app. You can check the connected users by injecting SimpUserRegistry and calling getUsers() method. Afterwards find the username of one of the users and try sending the message to it.
    – Edd
    Jul 27, 2017 at 18:16
  • @Edd Can you provide a STOMP SockJS example of connection with username?
    – durisvk10
    Jul 27, 2017 at 18:26
  • Btw @Edd SimpUserRegistry has empty set of SimpUsers even though I am connected to it
    – durisvk10
    Jul 27, 2017 at 18:38

1 Answer 1

11

This answer is written based on this application: https://github.com/spring-guides/gs-messaging-stomp-websocket

In order to register a user, you must first create an object that will represent it, for example:

public final class User implements Principal {

    private final String name;

    public User(String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }
}

Then you'll need a way to create these User objects. One way of doing it is when SockJS sends you the connect message headers. In order to do so, you need to intercept the connect message. You can do that by creating our your interceptor, for example:

public class UserInterceptor extends ChannelInterceptorAdapter {

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {

        StompHeaderAccessor accessor =
                MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            Object raw = message
                    .getHeaders()
                    .get(SimpMessageHeaderAccessor.NATIVE_HEADERS);

            if (raw instanceof Map) {
                Object name = ((Map) raw).get("name");

                if (name instanceof LinkedList) {
                    accessor.setUser(new User(((LinkedList) name).get(0).toString()));
                }
            }
        }
        return message;
    }
}

Once you have that, you must also register this UserInterceptor. I'm guessing somewhere in your application you have defined a configuration AbstractWebSocketMessageBrokerConfigurer class. In this class you can register your user interceptor by overriding configureClientInboundChannel method. You can do it like this:

@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
    registration.setInterceptors(new UserInterceptor());
}

And then finally, when your clients connect, they'll have to provide their usernames:

stompClient.connect({
    name: 'test' // Username!
}, function () {
    console.log('connected');
});

After you have all this setup, simpUserRegistry.getUsers() will return a list of users and you'll be able to use convertAndSendToUser method:

messaging.convertAndSendToUser("test", ..., ...);

Edit

Testing this out a bit further, when subscribing, you'll have to prefix your topics with /user as SimpMessagingTemplate uses this as a default prefix, for example:

stompClient.subscribe('/user/...', ...);

Also I had made a mistake in UserInterceptor and corrected it (name parsing part).

4
  • Do I also have to prefix every MessageMapping and SendTo annotations? @Edd
    – durisvk10
    Jul 27, 2017 at 20:47
  • PERFECT!!! This works even without /user/ default prefix... THANK YOU ( I would upvote but I have reputation less than 15 )
    – durisvk10
    Jul 27, 2017 at 21:09
  • Oh I think you're right I need to prefix it with /user/ because it's not working right now
    – durisvk10
    Jul 27, 2017 at 21:20
  • 2
    Is this still the best implementation in 2019? Dec 12, 2019 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.