什么是stomp?
STOMP帧格式
基本格式
COMMAND
header1:value1
header2:value2
Body^@
// 发送消息
SEND -- 命令类型:发送
destination:/queue/trade -- 头信息:标明了目的地
content-type:application/json -- 头信息:标明数据交换格式
content-length:44 -- 用来表示负载内容的 大小;
{"action":"BUY","ticker":"MMM","shares",44}^@ -- 帧内容
后台代码如下,主要的分析我都写在注释里了
package com.study.spring.websocket.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver;
import org.springframework.messaging.handler.invocation.HandlerMethodReturnValueHandler;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import java.util.List;
/**
@author dmz
@date Create in 12:37 2019/3/30
/
@Configuration
/*
通过这个注解,开启使用STOMP来传输基于message broker
的小心,这时的控制器支持@MessageMapping,就像@RequestMapping
/
@EnableWebSocketMessageBroker
public class Config implements WebSocketMessageBrokerConfigurer {
/*
注册STOMP端点,映射指定的url
端点的作用——客户端在订阅或发布消息 到目的地址前,要连接该端点
*
@param registry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/stomp").
/**
* 设置允许所有域名访问
/
setAllowedOrigins("").
/**
* 许多浏览器不支持 WebSocket 协议;
* SockJS 是 WebSocket 技术的一种模拟。SockJS 会 尽可能对应 WebSocket API,
* 但如果 WebSocket 技术 不可用的话,就会选择另外的 通信方式协议;
*/
withSockJS();
}
/**
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
}
@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
}
@Override
public void addArgumentResolvers(List
}
@Override
public void addReturnValueHandlers(List
}
@Override
public boolean configureMessageConverters(List
return false;
}
}
package com.study.spring.websocket.controller;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.RestController;
/**
package com.study.spring.websocket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebsocketApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketApplication.class, args);
}
}
前端项目地址:https://github.com/daimingzhi/h5/tree/master/webSocket
手机扫一扫
移动阅读更方便
你可能感兴趣的文章