java – Spring websockets:消息未发布
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – Spring websockets:消息未发布,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2132字,纯文字阅读大概需要4分钟。
内容图文
![java – Spring websockets:消息未发布](/upload/InfoBanner/zyjiaocheng/796/f81501993c34451fa7530dde1651da1e.jpg)
我使用带有STOMP和SockJS的Spring WebSockets作为前端.它工作很精细,但我有另一个困难.
这是后端代码:
@MessageMapping("/showAccountlist")
@SendTo("/topic/accounts")
public Account createPublishAccount(String name) throws Exception {
return new Account(name);
}
这是前端代码,它工作FINE,所有消息都发布到所有客户端.
stompClient.send("/app/showAccountlist", {}, name);
但是当我从我的java后端调用我的后端方法时,使用方法名称
createPublishAccount("Carlos");
似乎消息没有发布.有解决方案吗或者这不是它的工作方式,它只有在通过SockJS触发时才有效?
这是我的webconfig:
@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)中,可以将desination作为参数(在您的case / 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 websockets:消息未发布全部内容,希望文章能够帮你解决java – Spring websockets:消息未发布所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。