【发布时间】:2016-12-19 13:48:57
【问题描述】:
我有以下控制器
@Controller
public class GreetingController
{
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Person greeting(String message) throws Exception {
Person person=new Person();
person.setAge(10);
return person;
}
@Autowired
private SimpMessagingTemplate template;
@RequestMapping(path="/meeting",method=RequestMethod.POST)
public @ResponseBody void greet() {
this.template.convertAndSend("/topic/greetings", "message");
}
}
而我的配置是
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig1 extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/hello").withSockJS();
}
}
所以根据 spring doc template.convertAndSend("/topic/greetings", "message") 应该调用代理并且映射的网络套接字将被调用。
使用 SockJS 的前端代码
var socket = new SockJS('/hello');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting){
console.log(JSON.parse(greeting.body));
});
// to send via the web service-WORKING ( but websocket not called in springs)
$.post("http://localhost:8080/meeting");
// to send via websocket - WORKING
stompClient.send("/app/hello", {}, JSON.stringify({ 'message':'message'}));
控制台中没有错误。我可以通过 SockJs 连接它并将消息发送到“/topic/greetings”,但我想调用一个 webService,它反过来调用 web Socket。所以在搜索了很多之后,我被卡住了,因为没有错误,并且在春天找不到其他方法。
【问题讨论】:
-
确保您的客户订阅了
/topic/greetings。否则服务器端没有任何东西可以发送消息。 -
我使用 sockjs 建立连接并订阅客户端。我甚至可以使用 sockjs 发送它。但是,如果我在 sockjs 中建立连接后从邮递员那里调用 web 服务 /meeting,则不会发生任何事情
-
好吧,不知道如何帮助你。一切看起来都很好。在 Spring Integration 中,我们有一个类似的测试用例:github.com/spring-projects/spring-integration/blob/master/…。
StompInboundChannelAdapter执行subscribeDestination(destination);并且恰好有messagingTemplate.send("/topic/myTopic",。因此,请调查您的应用程序的调试日志,或者仅将您的greet()方法调试到 Spring 源代码 -
也许您的
HelloMessage无法正确转换为byte[]进行发送。见AbstractMessageBrokerConfiguration.brokerMessageConverter() -
@AfrozShaikh 你是如何解决这个问题的?我有同样的问题,注释有效,但不是通过消息模板
标签: spring-websocket