0

I am trying send direct messages to user. Application hasn't done authentication so there is temporary solution for creating websocket session users as you can see in added code.

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        registry.addEndpoint("/ws")
                .setHandshakeHandler(new CustomHandshakeHandler())
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/queue/", "/topic/", "/exchange/");
        registry.setApplicationDestinationPrefixes("/app");
    }

    // only for dev purpose
    public static class CustomHandshakeHandler extends DefaultHandshakeHandler {

        @Override
        protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
            String username = "user-123";
            return new StompPrincipal(username);
        }

        @Data
        @AllArgsConstructor
        @NoArgsConstructor
        public static class StompPrincipal implements Principal {
            private String name;
        }
    }
}

Here is my RabbitMQ listener which handle event with message and send direct message to test user user-123 via websockets:

@RabbitListener(queues = "${event.queue.message-created}")
public void handleMessageCreatedEvent(MessageCreatedEvent event) {
    String devUser = "user-123";
    log.info("MSG received {}.", event); 
    simpMessagingTemplate.convertAndSendToUser(devUser, "/exchange/amq.direct/chat.message", event);
}

Message is handled with rabbit listener and send with simple messaging template, but didn't arrive to frontend client in javascript.

Here is how I am trying to handle these messages:

$(function () {
    var stompClient;
    var wrappedSocket = {

        init: function (url) {
            stompClient = Stomp.over(new SockJS(url));
        },
        connect: function (successCallback, errorCallback) {

            stompClient.connect({}, function (frame) {
                successCallback(frame)
            }, function (error) {
                errorCallback(error)
            });
        },
        subscribe: function (destination, callback) {
            stompClient.subscribe(destination, function (message) {
                callback(message)
            });
        },
        send: function (destination, headers, object) {
            stompClient.send(destination, headers, object);
        }
    };


    wrappedSocket.init('/ws');

    wrappedSocket.connect(
        function (frame) {
            console.info('connected', frame)
        }, function (err) {
            console.error('not connected', err)
        }
    );

    wrappedSocket.subscribe("/user/exchange/amq.direct/chat.message", function(message) {
        console.log('NEW PRIVATE MESSAGE', message)
    });

    console.log("ready!");
});

I can see in browser console that client is successfully connected and start subscribing given channel, but no message is received.

Can you tell how to fix it? Thank you.

4

1 回答 1

1

Subscription should be initialized after connection established, so try call wrappedSocket.subscribe() in success callback.

于 2020-07-27T19:42:11.270 回答