java - 无法使用 Spring Websocket 发送用户消息

标签 java spring spring-mvc websocket spring-websocket

我阅读了有关用户目的地的 Spring 文档。 我想使用 convertAndSendToUser 方法仅向特定用户发送消息。

这是java代码:

@Controller
public class WebsocketTest {

    @Autowired
    public SimpMessageSendingOperations messagingTemplate;

    @PostConstruct
    public void init(){
        ScheduledExecutorService statusTimerExecutor=Executors.newSingleThreadScheduledExecutor();
        statusTimerExecutor.scheduleAtFixedRate(new Runnable() {                
            @Override
            public void run() {
                messagingTemplate.convertAndSendToUser("myuser","/queue/test", new Return("test"));
            }
        }, 5000,5000, TimeUnit.MILLISECONDS);
    }
}

这是客户端js代码:

var socket = new WebSocket('ws://localhost:8080/hello');
            stompClient = Stomp.over(socket);            
            stompClient.connect("myuser","mypass", function(frame) {
                setConnected(true);
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/greetings', function(greeting){
                    showGreeting(JSON.parse(greeting.body).value);
                });
                stompClient.subscribe('/user/queue/test', function(greeting){
                    showGreeting(JSON.parse(greeting.body).value);
                });
            });

首先考虑用户值(value)这个是否正确?

stompClient.connect("myuser",...

为什么这个测试不起作用?该用户没有收到任何消息。 如果我将目的地切换到 /topic/greetings 并将方法更改为 convertAndSend() 这可以工作,但显然是广播,而不仅仅是按请求发送给特定用户。

小更新

我尝试使用以下代码设置对单个用户的回复:

    @MessageMapping("/hello")
    @SendToUser("/queue/test")
    public Return test(){
        return new Return("test");
    }

这有效,这不是我需要的,因为这只回复来自客户端的消息。似乎我无法使用 convertAndSendToUser() 来处理来自服务器的未经请求的消息。

最佳答案

在客户端订阅/user/queue/test并使用convertAndSendToUser/topic/test主题发送消息看起来差不多。

现在如何获取“myUser”值?

您可以在握手期间从 request.getUserPrincipal() 获取此值,或者在接收消息时注入(inject) Principal; sessionId 在这里也有效。您可以查看this commit for more details on the matter .

关于java - 无法使用 Spring Websocket 发送用户消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34942934/

相关文章:

spring - Spring MVC 中返回 ModelAndView 和返回 String 有什么区别?

spring - Keycloak管理员客户端: Unable to find a MessageBodyReader of content-type application/json

java - 如何设置@RequestMapping的默认值?

forms - <%@ taglib uri =“www.springframework.org/tags/form”前缀=“form”%> <form :errors path =“student1.*” /> causing “Unable to compile JSP page” error

java - 依次打印 ArrayList 中的所有字符

java - 从java数组中删除空值

java - 接缝关闭监听器

Java 方法从未到达 main 中的 (?)

Spring Security 4 和 JSF 2 集成

spring-mvc - 想要在JSP中显示最后修改的文件列表