我有以下控制器
@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");
}
}
Run Code Online (Sandbox Code Playgroud)
我的配置是
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
因此,根据spring doc template.convertAndSend("/ topic/greetings","message")应该调用代理并调用映射的Web套接字.
使用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'}));
Run Code Online (Sandbox Code Playgroud)
控制台中没有错误.我可以通过SockJs连接它并发送消息到"/ topic/greetings",但我想调用一个webService,它反过来调用web Socket.因此,在搜索了很多因素之后,没有错误,并且无法在春季找到不同的方法.
我运行了你的代码,你应该发送对象而不是发送简单的字符串,而不是
this.template.convertAndSend("/topic/greetings", "message");
Run Code Online (Sandbox Code Playgroud)
应该
this.template.convertAndSend("/topic/greetings", messageObject);
并且您的对象应该有一些方法来访问内容,例如
MessageObject.getConent();
Run Code Online (Sandbox Code Playgroud)
否则你可以随时使用toString()
你的js应该是
this.template.convertAndSend("/topic/greetings", "message");
Run Code Online (Sandbox Code Playgroud)
注意接收对象末尾的内容
| 归档时间: |
|
| 查看次数: |
2291 次 |
| 最近记录: |