Spring Websockets @SendToUser没有登录? [英] Spring Websockets @SendToUser without login?

查看:925
本文介绍了Spring Websockets @SendToUser没有登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有websocket功能的简单弹簧应用程序,到目前为止一切正常。
现在我想使用@SendToUser注释从我的服务器向特定客户端发送消息。这给了我错误忽略消息,没有可用的主要信息。我知道我的服务器上没有任何登录信息,因此每个用户都是匿名且没有委托人(我现在不使用Spring安全性)。但是每个用户都有一个session-id。是否有可能以某种方式使用会话ID来区分用户?我怎样才能实现这一目标,以便我的用户获得与会话ID相对应的主体?

解决方案

我认为解决方案可能是避免使用 @SendToUser 并使用原始 SimpMessagingTemplate 并将消息发送到您为开放会话控制的目的地。 / p>

例如。假设您有一个新的websocket会话的身份,您可以订阅队列名称中具有该标识符的队列:

  stomp.subscribe(/ queue / chats+ - + mycustomidentifier,onmessage); 

现在,在Spring websocket监听器端,您可以使用指示您的回复SimpMessagingTemplate

  @Controller 
public class MyController {


@Autowired
private SimpMessagingTemplate simpMessagingTemplate;

@MessageMapping(/ chats)
public void handleChat(@Payload ChatMessage message){
this.simpMessagingTemplate.convertAndSend(/ queue / chats-+mycustomidentifier ,[+ getTimestamp()+]:+ message.getMessage());
}
....


I have a simple spring application with websocket functionality and everything works so far. Now I want to send a message from my server to a specific client using the @SendToUser annotation. This gives me the error "Ignoring message, no principal info available". I understand that i have no login whatsoever on my server, so every user is "anonymous" and does not have a principal (I am not using spring security for now). But every user has a session-id. Isnt it possible to use the session id somehow to differentiate between users? How can i achieve that so my users get a principal which corresponds to the session-id?

解决方案

I think a solution might be to avoid using @SendToUser and use raw SimpMessagingTemplate and to send messages to a destination that you control for open sessions.

For eg. assuming that you had some identity for a new websocket session, you can subscribe to a queue with that identifier in the queue name:

stomp.subscribe("/queue/chats" + "-" + mycustomidentifier, onmessage);

Now, on the Spring websocket listener side, you can direct your responses using SimpMessagingTemplate:

@Controller
public class MyController {


    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/chats")
    public void handleChat(@Payload ChatMessage message) {
        this.simpMessagingTemplate.convertAndSend("/queue/chats-" + "mycustomidentifier", "[" + getTimestamp() + "]:" + message.getMessage());
    }
....

这篇关于Spring Websockets @SendToUser没有登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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