我在服务器端有以下代码:
@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后,我尝试了以下内容:
服务器端:
simpMessagingTemplate.convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo"));
客户方:
stompClient.subscribe('/user1/queue/greetings', function(menuItem){
alert(menuItem);
});
服务器端:
simpMessagingTemplate.convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo"));
客户方:
stompClient.subscribe('/user/queue/greetings', function(menuItem){
alert(menuItem);
});
服务器端:
simpMessagingTemplate.convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo"));
客户方:
stompClient.subscribe('user/user1/queue/greetings', function(menuItem){
alert(menuItem);
});
无论如何都不起作用
答案 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
感谢每个人