使用Spring Websocket向特定用户发送消息

3

我在这个教程中设置了一个使用Spring的WebSocket:https://spring.io/guides/gs/messaging-stomp-websocket/。我需要做的是让我的服务器每5秒向特定的用户发送一条消息。因此,我首先做了以下操作:

@Autowired
private SimpMessagingTemplate template;

@Scheduled(fixedRate = 5000)
public void greet() {
    template.convertAndSend("/topic/greetings", new Greeting("Bufff!"));
}

它可行。现在,为了仅向特定用户发送消息,我更改了以下内容:

@Scheduled(fixedRate = 5000)
public void greet() {
   template.convertAndSendToUser("MyName","/queue/greetings", new Greeting("Bufff!"));
}

在WebSocketConfig.java中添加队列:
public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker("/topic","/queue");
    config.setApplicationDestinationPrefixes("/app");
}

更改GreetingController.java中的注释:

@MessageMapping("/hello")
@SendToUser("/queue/greetings")
public Greeting UserGreeting(HelloMessage message, Principal principal) throws Exception {
    Thread.sleep(1000); // simulated delay
    return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}

并更改app.js中的连接功能:

var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
    setConnected(true);
    console.log('Connected: ' + frame);
    stompClient.subscribe('user/queue/greetings', function (greeting) {
        showGreeting(JSON.parse(greeting.body).content);
    });
});

服务器使用spring-boot-security,我通过查找所有使用SimpUserRegistry的用户来确定MyName是否正确(参见https://dev59.com/GY7ea4cB1Zd3GeqPBXRr#32215398)。但是不幸的是,我的代码没有起作用。我已经尝试过这个使用Spring向特定用户发送消息,但我不想让Spring区分会话而是用户。我还看了这个在Spring Websocket上向特定用户发送消息,但它没有帮助,因为链接无法使用。
这是我的控制台日志:
2020-01-20 17:08:51.352 DEBUG 8736 --- [nboundChannel-3] .WebSocketAnnotationMethodMessageHandler : Searching methods to handle SEND /app/hello session=kvv0m1qm, lookupDestination='/hello'
2020-01-20 17:08:51.352 DEBUG 8736 --- [nboundChannel-3] .WebSocketAnnotationMethodMessageHandler : Invoking de.iteratec.iteraweb.controllers.GreetingController#UserGreeting[2 args]
2020-01-20 17:08:52.354 DEBUG 8736 --- [nboundChannel-3] org.springframework.web.SimpLogging      : Processing MESSAGE destination=/queue/greetings-userkvv0m1qm session=null payload={"content":"Hello, hey!"}
2020-01-20 17:08:54.882 DEBUG 8736 --- [MessageBroker-2] org.springframework.web.SimpLogging      : Processing MESSAGE destination=/queue/greetings-userkvv0m1qm session=null payload={"content":"Bufff!"}
2020-01-20 17:08:59.883 DEBUG 8736 --- [MessageBroker-4] org.springframework.web.SimpLogging      : Processing MESSAGE destination=/queue/greetings-userkvv0m1qm session=null payload={"content":"Bufff!"}

我错过了什么变化吗?
1个回答

4

您能看到客户端成功订阅了您的终端吗?

我认为您在客户端代码中漏掉了第一个/,应该将 'user/queue/greetings' 改为 '/user/queue/greetings'


嘿,Peter,是的!你说得对。这是我的错误。 - tomson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接