Весенний загрузочный веб-сокет с топом, не отправляющим сообщение конкретному пользователю

Я пытаюсь реализовать базовое приложение чата с помощью Spring boot и Stomp Protocol. Я не могу отправить сообщение конкретному пользователю через SimpMessagingTemplate.convertAndSendToUser

Все мои сообщения отправляются во все подключенные сокеты.

мой контроллер:

 @Controller
public class MessageController {

    private final SimpMessagingTemplate simpMessagingTemplate;

    /**
     * Constructor for object
     * 
     * @param simpMessagingTemplate
     */
    public MessageController(final SimpMessagingTemplate simpMessagingTemplate) {
        this.simpMessagingTemplate = simpMessagingTemplate;
    }

    /**
     * Responsible for sharing message through web socket.s
     * 
     * @param message
     *            to share with audience.
     * @return
     */
    @MessageMapping("/message")
    @SendTo("/topic/message")
    public Message send(Message message) {
        String time = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        message.setTime(time);
        simpMessagingTemplate.convertAndSendToUser(message.getTo(), "/topic/message", message);
        return message;
    }
}

конфигурация веб-сокета:

@EnableWebSocketMessageBroker
@Configuration
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    private static final int MESSAGE_BUFFER_SIZE = 8192;
    private static final long SECOND_IN_MILLIS = 1000L;
    private static final long HOUR_IN_MILLIS = SECOND_IN_MILLIS * 60 * 60;

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.web.socket.config.annotation.
     * AbstractWebSocketMessageBrokerConfigurer#configureMessageBroker(org.
     * springframework.messaging.simp.config.MessageBrokerRegistry)
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // simple broker is applicable for first setup.
        // To scale application enableStompBrokerRelay has to be configured.
        // documentation :
        // https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-handle-broker-relay
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.web.socket.config.annotation.
     * WebSocketMessageBrokerConfigurer#registerStompEndpoints(org.
     * springframework.web.socket.config.annotation.StompEndpointRegistry)
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat");
        registry.addEndpoint("/chat").withSockJS();
    }

    /**
     * Bean for servlet container configuration. Sets message buffer size and
     * idle timeout.
     * 
     * @return
     */
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(MESSAGE_BUFFER_SIZE);
        container.setMaxBinaryMessageBufferSize(MESSAGE_BUFFER_SIZE);
        container.setMaxSessionIdleTimeout(HOUR_IN_MILLIS);
        container.setAsyncSendTimeout(SECOND_IN_MILLIS);
        return container;
    }

}

базовая конфигурация безопасности:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("1").password("1").roles("USER");
        auth.inMemoryAuthentication().withUser("2").password("2").roles("USER");
        auth.inMemoryAuthentication().withUser("3").password("3").roles("USER");
    }
}

и фрагмент кода javascript:

    dataStream = $websocket('ws://localhost:8080/chat');
            stomp = Stomp.over(dataStream.socket);
            var startListener = function() {
                connected = true;
                stomp.subscribe('/topic/message', function(data) {
                    messages.push(JSON.parse(data.body));
                    listener.notify();
                });
            };
stomp.connect({
            'Login' : name,
            passcode : name,
            'client-id' : name
        }, startListener);

    send  = function(request) {
                stomp.send('/app/message', {}, JSON.stringify(request));
            }

person ibrahimbayer    schedule 05.07.2017    source источник


Ответы (1)


Вы должны подписаться на специальное направление.

stomp.subscribe('/topic/message' + client_id, function(data) {
                messages.push(JSON.parse(data.body));
                listener.notify();
            });

@SendTo ("/ topic / message") с возвратом отправит сообщение всем клиентам, подписавшимся на "/ topic / message", в то время как следующий код отправит сообщение всем клиентам, подписавшимся на "/ topic / message / {message.getTo ()}" ":

simpMessagingTemplate.convertAndSendToUser(message.getTo(), "/topic/message", message);
person The Zero    schedule 10.05.2018