如何向具体用户发送websocket消息?

时间:2018-04-26 13:20:10

标签: java spring spring-security spring-websocket

我在服务器端有以下代码:

@Autowired
private SimpMessagingTemplate simpMessagingTemplate;

@MessageMapping("/hello")
public void greeting(@Payload HelloMessage message, Principal principal) throws Exception {
    Thread.sleep(1000); // simulated delay
    simpMessagingTemplate.convertAndSendToUser(principal.getName(), "/topic/greetings", new Greeting("Ololo"));        
}

客户端代码:

function connect() {
    var socket = new SockJS('/gs-guide-websocket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/greetings', function (greeting) {
            showGreeting(JSON.parse(greeting.body).content);
        });
    });
}
function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

我的行动:

我运行应用程序,以user1身份登录并启动从客户端到服务器的消息发送,我看到方法greeting正在调用并且行simpMessagingTemplate.convertAndSendToUser(principal.getName(), "/topic/greetings", new Greeting("Ololo"))成功执行但我看不到客户端的那条消息。

我怎么能

更多来源:

spring security configuration:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String SECURE_ADMIN_PASSWORD = "rockandroll";

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .formLogin()
                .loginPage("/index.html")
                    .loginProcessingUrl("/login")
                    .defaultSuccessUrl("/sender.html")
                    .permitAll()
                .and()
                .logout()
                    .logoutSuccessUrl("/index.html")
                    .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/js/**", "/lib/**", "/images/**", "/css/**", "/index.html", "/","/*.css","/webjars/**", "/*.js").permitAll()
                .antMatchers("/websocket").hasRole("ADMIN")
                .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
                .anyRequest().authenticated();

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(new AuthenticationProvider() {

            @Override
            public boolean supports(Class<?> authentication) {
                return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
            }

            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

                List<GrantedAuthority> authorities = SECURE_ADMIN_PASSWORD.equals(token.getCredentials()) ?
                        AuthorityUtils.createAuthorityList("ROLE_ADMIN") : null;

                return new UsernamePasswordAuthenticationToken(token.getName(), token.getCredentials(), authorities);
            }
        });
    }
}

网络套接字配置:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket").withSockJS();
    }

}

更新

在建议和阅读主题Sending message to specific user on Spring Websocket后,我尝试了以下内容:

1

服务器端:

simpMessagingTemplate.convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo"));

客户方:

stompClient.subscribe('/user1/queue/greetings', function(menuItem){
    alert(menuItem);
});

2

服务器端:

simpMessagingTemplate.convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo"));

客户方:

stompClient.subscribe('/user/queue/greetings', function(menuItem){
    alert(menuItem);
});

3

服务器端:

simpMessagingTemplate.convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo"));

客户方:

stompClient.subscribe('user/user1/queue/greetings', function(menuItem){
    alert(menuItem);
});

无论如何都不起作用

2 个答案:

答案 0 :(得分:2)

仅在客户端上进行必要的更改(app.js):订阅/user/user1/queue/greetings而不是/user/queue/greetings

stompClient.subscribe('/user/queue/greetings', ...

然后在网络界面中以user1身份登录。它必须是user1因为那是针对服务器的用户:

convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo")) 

点击Send后,Ololo消息将显示为客户端提醒。

答案 1 :(得分:0)

现在可以在

下与我一起使用
template.convertAndSendToUser("username","/queue/notification",notifications); //server

stompClient.subscribe('/user/username/queue/notification', ....  // client

感谢每个人