当前位置: 首页 > 知识库问答 >
问题:

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

左康安
2023-03-14

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

@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是invokes和linesimpMessagingTemplate。convertAndSendToUser(principal.getName(),“/topic/greetings”,new Greeting(“Ololo”)成功执行,但我在客户端没有看到该消息。

我怎么能

Spring Security配置

@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套接字配置:

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

}

在建议和阅读主题后,我尝试了以下方式向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);
});

反正也不行

共有2个答案

阎庆
2023-03-14

它现在在我的领导下起作用

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

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

感谢每一个人

敖和韵
2023-03-14

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

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

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

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

单击“发送”,Ololo消息将显示为客户端警报。

 类似资料:
  • 我正在阅读《Spring in Action4》一书,以使用WebSocket上的STOMP消息传递。 假设,如下所示: 然后客户端使用以下JavaScript代码订阅目标: 则该消息将发送到目的地,如下所示: 那么,两个目的地和看起来是不同的,消息怎么可能到达客户端呢?

  • 我是新手。NET(C#)和WebSocket。。。我已经安装了VS2012和Windows Server 2012,并且已经启动并运行了WebSocket。我似乎无法从一个套接字接收消息并将其发送到另一个特定的套接字。唯一的选择似乎是向所有套接字广播消息。有没有一种方法可以将消息只发送给特定的用户?我希望聊天室主持人有机会拒绝不适当的帖子。

  • 我有一个Spring启动应用程序运行在heroku。我使用webSocket为特定用户向客户端和服务器发送消息。我使用Spring引导的SimpMessagingTemplate.convertAndSendToUser来发送和接收消息,当用户需要从服务器获取消息时,这种方法效果很好。我使用Heroku会话亲和力,这意味着即使我扩大了会话的数量,用户和webSocket仍然共享同一个会话。 当我需

  • 我使用本教程中描述的spring设置了一个WebSocket:https://spring.io/guides/gs/messaging-stomp-websocket/。我需要的是我的服务器每5秒向特定用户发出一条消息。所以我首先做了这个: 而且起作用了。现在,为了只向特定用户发送消息,我更改了以下内容: 在WebSocketConfig.java中添加队列: 更改GreetingControl

  • 问题内容: 我想在用户连接到Spring WebSocket时向其发送消息, MyChannelInterception类为 通过这一点,我在收到新连接的用户,但该方法的信息中不将消息发送到新的登录用户。 问题答案: 我将创建侦听器并在内部使用。 顺便说一句,仅被调用一次(不适用于每个连接的用户)。因此,您必须处理拦截器中的发送消息。 尝试这样的事情: 我希望这个能帮上忙

  • 我尝试将Spring与websocket一起使用。我从本教程开始调查。 在我的侧客户端,我有类似的东西来初始化到服务器的连接: 它工作得很好,在我的控制器中,我可以在下面的类中执行我的过程: 现在我想做的是让一个线程向监听“/主题/问候”的客户端发送消息。我这样写Runnable类: 这样完成了我的控制器: 该方法采用光电控制器。fireGreeting按我的要求调用,但客户端没有发生任何事情。有