Spring Boot web socket with stomp 不向特定用户发送消息 [英] Spring boot web socket with stomp not sending message to specific user

查看:58
本文介绍了Spring Boot web socket with stomp 不向特定用户发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Spring boot & 实现一个基本的聊天应用程序.践踏协议.我无法通过 SimpMessagingTemplate.convertAndSendToUser

I am trying to implement a basic chat application with Spring boot & Stomp Protocol. I am not able to send message to specific user via SimpMessagingTemplate.convertAndSendToUser

我所有的消息都被推送到所有连接的套接字.

All of my messages are pushed to all connected sockets.

我的控制器:

 @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 代码片段:

and javascript code snippet:

    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));
            }

推荐答案

您应该订阅特殊目的地.

You should subscribe the special destination.

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

@SendTo("/topic/message") with return 会向所有订阅/topic/message"的客户端发送消息,同时按照代码向所有订阅/topic/message/{message.getTo"的客户端发送消息()}":

@SendTo("/topic/message") with return will send message to all client subscribe to "/topic/message", meanwhile follow code send message to all client subsribe to "/topic/message/{message.getTo()}":

simpMessagingTemplate.convertAndSendToUser(message.getTo(), "/topic/message", message);

这篇关于Spring Boot web socket with stomp 不向特定用户发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆