如何向具体用户发送 websocket 消息?
How to send websocket message to concrete user?
我在服务器端有以下代码:
@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安全配置:
@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);
});
反正没用
仅在客户端进行必要的更改 (app.js
):而不是 /user/user1/queue/greetings
,订阅 /user/queue/greetings
:
stompClient.subscribe('/user/queue/greetings', ...
然后在 Web 界面中以 user1
身份登录。它必须是 user1
因为这是针对服务器的用户:
convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo"))
单击 Send
后,Ololo 消息显示为客户端警报。
它现在在
下与我一起使用
template.convertAndSendToUser("username","/queue/notification",notifications); //server
stompClient.subscribe('/user/username/queue/notification', .... // client
谢谢大家
我在服务器端有以下代码:
@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安全配置:
@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);
});
反正没用
仅在客户端进行必要的更改 (app.js
):而不是 /user/user1/queue/greetings
,订阅 /user/queue/greetings
:
stompClient.subscribe('/user/queue/greetings', ...
然后在 Web 界面中以 user1
身份登录。它必须是 user1
因为这是针对服务器的用户:
convertAndSendToUser("user1", "/queue/greetings", new Greeting("Ololo"))
单击 Send
后,Ololo 消息显示为客户端警报。
它现在在
下与我一起使用template.convertAndSendToUser("username","/queue/notification",notifications); //server
stompClient.subscribe('/user/username/queue/notification', .... // client
谢谢大家