Spring websocket发送给特定的人 [英] Spring websocket send to specific people

查看:124
本文介绍了Spring websocket发送给特定的人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为spring-web app添加了基于自定义令牌的身份验证,并为spring websocket扩展了如下所示

I have added custom token based authentication for my spring-web app and extending the same for spring websocket as shown below

public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

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

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

    @Override
      public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.setInterceptors(new ChannelInterceptorAdapter() {

            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {

                StompHeaderAccessor accessor =
                    MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

                if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                    String jwtToken = accessor.getFirstNativeHeader("Auth-Token");
                        if (!StringUtils.isEmpty(jwtToken)) {
                            Authentication auth = tokenService.retrieveUserAuthToken(jwtToken);
                            SecurityContextHolder.getContext().setAuthentication(auth);
                            accessor.setUser(auth);
                            //for Auth-Token '12345token' the user name is 'user1' as auth.getName() returns 'user1'
                        }
                }

                return message;
            }
        });
      }
}

连接到套接字的客户端代码是

The client side code to connect to the socket is

var socket = new SockJS('http://localhost:8080/gs-guide-websocket');
    stompClient = Stomp.over(socket);
    stompClient.connect({'Auth-Token': '12345token'}, function (frame) {
        stompClient.subscribe('/user/queue/greetings', function (greeting) {
            alert(greeting.body);
        });
    });

从我的控制器我发送消息为

And from my controller I am sending message as

messagingTemplate.convertAndSendToUser("user1", "/queue/greetings", "Hi User1");

对于身份验证令牌 12345token 用户名是 user1 。但是当我向 user1 发送消息时,它未在客户端收到。我有什么遗漏吗?

For the auth token 12345token the user name is user1. But when I send a message to user1, its not received at the client end. Is there anything I am missing with this?

推荐答案

在你的Websocket控制器中,你应该这样做:

In your Websocket controller you should do something like this :

@Controller
public class GreetingController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/hello")
    public void greeting(Principal principal, HelloMessage message) throws  Exception {
        Greeting greeting = new Greeting();
        greeting.setContent("Hello!");
        messagingTemplate.convertAndSendToUser(message.getToUser(), "/queue/reply", greeting);
    }
}

在客户端,您的用户应订阅主题/ user / queue / reply。

On the client side, your user should subscribe to topic /user/queue/reply.

您还必须添加一些目的地前缀:

You must also add some destination prefixes :

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic", "/queue" ,"/user");
        config.setApplicationDestinationPrefixes("/app");
        config.setUserDestinationPrefix("/user");
    }
/*...*/
}

当您的服务器在/ app / hello队列上收到消息时,它应该向您的dto中的用户发送消息。用户必须等于用户的主体。

When your server receive a message on the /app/hello queue, it should send a message to the user in your dto. User must be equal to the user's principal.

我认为您的代码中唯一的问题是您的/ user不在您的目标前缀中。您的问候消息被阻止,因为您将它们发送到以/ user开头的队列中,并且此前缀未注册。

I think the only problem in your code is that your "/user" is not in your destination prefixes. Your greetings messages are blocked because you sent them in a queue that begin with /user and this prefixe is not registered.

您可以在git repo检查来源:
https://github.com/simvetanylen/test-spring-websocket

You can check the sources at git repo : https://github.com/simvetanylen/test-spring-websocket

希望它有效!

这篇关于Spring websocket发送给特定的人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆