gpt4 book ai didi

java - Spring 网络套接字 : message not published

转载 作者:搜寻专家 更新时间:2023-11-01 02:39:30 25 4
gpt4 key购买 nike

我将 Spring WebSockets 与 STOMP 和 SockJS 一起用于前端。它工作正常,但我有另一个困难。

这是后端代码:

 @MessageMapping("/showAccountlist")
@SendTo("/topic/accounts")
public Account createPublishAccount(String name) throws Exception {

return new Account(name);
}

这是前端代码,运行良好,所有消息都会发布到所有客户端。

 stompClient.send("/app/showAccountlist", {}, name);

但是当我我的java后端调用我的后端方法时,方法名称为

createPublishAccount("Carlos");

似乎消息没有发布。任何解决方案?或者这不是它的工作方式,它只有在通过 SockJS 触发时才有效?

这是我的网络配置:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

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

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/showAccountlist").withSockJS();
}

最佳答案

调用@SendTo 注解的方法似乎无法发送消息。

Spring推荐的消息发送方式是使用SimpMessagingTemplate。例如在 convertAndSendToUser 方法 ( http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/messaging/simp/SimpMessagingTemplate.html ) 中,可以将目的地作为参数(在您的情况下为 /topic/accounts)。

请参阅 Spring 文档的摘录( http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-handle-send ):

What if you want to send messages to connected clients from any part of the application? Any application component can send messages to the "brokerChannel". The easiest way to do that is to have a SimpMessagingTemplate injected, and use it to send messages. Typically it should be easy to have it injected by type, for example:

@Controller
public class GreetingController {

private SimpMessagingTemplate template;

@Autowired
public GreetingController(SimpMessagingTemplate template) {
this.template = template;
}

@RequestMapping(path="/greetings", method=POST)
public void greet(String greeting) {
String text = "[" + getTimestamp() + "]:" + greeting;
this.template.convertAndSend("/topic/greetings", text);
}

}

关于java - Spring 网络套接字 : message not published,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37345710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com