Spring Websockets @SendToUser 无需登录? [英] Spring Websockets @SendToUser without login?

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

问题描述

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

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?

推荐答案

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

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.

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

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);

现在,在 Spring websocket 侦听器端,您可以使用 SimpMessagingTemplate 引导您的响应:

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天全站免登陆