【小结2】
经过前面的这些坑,虽然看起来不多,但是别忘了,这些坑也是总结出来的,不总结的时候,谁知道是几个坑啊
【Step 6: 写高级的代码】
在弄stomp之前,强烈建议 大家看看stomp的知识,不才孤陋寡闻,以为stomp是spring支持websocket才出的东西,其实不然,这东西早就有,不看的话有些概念弄不清。
在这之前读文档的时候 就说了一个坑, 这个stomp的用法和前面的东西是分开的,不能混在一起写,是另一种实现方式。//巨大隐形坑-7
客户端:
//这是新的写法了,和之前的都不一样
var socket = new SockJS('http://mydomain/myweb/rest/portfolio');//见巨坑-9
var client = Stomp.over(socket);
client.connect({},function(){
console.log("stomp is connected");
client.subscribe("/topic/custom", function(message){//坑-8:写在connect里面; 坑-11:custom随便写的就是为了和后面发送消息时对应,没有别的含义:
if (message.body) {
alert("got message with body " + message.body);
} else {
alert("got empty message");
}
}, {});
});
服务端:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {//是的,和之前完全不一样了,这就是那个巨大隐形坑-7
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/portfolio").setAllowedOrigins("*").withSockJS();
//这个portfolio是干嘛的,跳到哪?
//这个东西就在这出现和前面对应,不跳到哪,不要在服务端找这个东西,除了这就没有别得地方有,只是用来建立websocket链接的一个标志:巨坑-9
registry.addEndpoint("/portfolio/info").setAllowedOrigins("*").withSockJS();//这个info参照之前的坑
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");//所有发送消息的地方加前缀app
registry.enableSimpleBroker("/topic");//这个东西叫主题,广播用的,就类似前面为了解决广播问题专门加的那一堆代码
}
@Override
public void addArgumentResolvers(List arg0) {
// TODO Auto-generated method stub
}
@Override
public void addReturnValueHandlers(List arg0) {
// TODO Auto-generated method stub
}
@Override
public void configureClientInboundChannel(ChannelRegistration arg0) {
// TODO Auto-generated method stub
}
@Override
public void configureClientOutboundChannel(ChannelRegistration arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean configureMessageConverters(List arg0) {
// TODO Auto-generated method stub
return true;//小坑一个,默认的位false:坑-10
}
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration arg0) {
// TODO Auto-generated method stub
}
}
//自己的业务类
@Controller
public class ServiceBean {
private SimpMessagingTemplate template;
@Autowired
public ServiceBean (SimpMessagingTemplate template) {
this.template = template;
}
@RequestMapping("/do")
public String do(){
//在处理完业务后,通知客户端
this.template.convertAndSend("/topic/custom", "发送的消息");//custom和坑-11对应
}
}
除此之外,spring在stomp上面还提供很多功能,都没研究,慢慢来。
欢迎大家指正。
【中结】
还是那句话,不知道是官网文档有问题,还是我理解有问题,总是感觉坑很多。
看官方文档需谨慎啊。
但是不甘心总是看别人的东西,总看别人的东西哪里来的原创。