How to send websocket message to concrete user?

孤街醉人 提交于 2019-12-11 02:24:55

问题


I have following code on server side:

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

client side code:

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

My actions:

I run application, log in as user1 and initiate message sending from client to server and I see that method greeting is invokes and line simpMessagingTemplate.convertAndSendToUser(principal.getName(), "/topic/greetings", new Greeting("Ololo")) executes successfully but I don't see that message on the client side.

How can I

more sources:

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

web socket config:

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

}

update

After advices and reading topic Sending message to specific user on Spring Websocket I tried following:

1.

server side:

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

client side:

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

2.

server side:

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

client side:

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

3.

server side:

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

client side:

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

It doesn't work anyway


回答1:


Only necessary change is on the client (app.js): Instead of /user/user1/queue/greetings, subscribe to /user/queue/greetings:

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

Then login as user1 in the web interface. It has to be user1 because that's the user that is targeted at the server:

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

Upon clicking Send, The Ololo message appears as a client alert.




回答2:


it works with me now under

template.convertAndSendToUser("username","/queue/notification",notifications); //server

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

thanks every body



来源:https://stackoverflow.com/questions/50044077/how-to-send-websocket-message-to-concrete-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!