今天继续Websocket之STOMP协议,因为其设计简单,在开发客户端方面使用简便,在不少种语言上均可以见到其身影,并不是websocket“独享”。前端
STOMP(Simple/Streaming Text Orientated Messaging Protocol),即简单(流)文本定向消息协议。属于消息队列的一种协议,有点相似于jms。java
提供消息体的格式,容许STOMP客户端(Endpoints)与任意STOMP消息代理(message broker)进行交互,实现客户端之间进行异步消息传送。web
图片来源《spring in action》spring
下面使用SpringSecurity和WebSocket-STOMP实现“点对点”消息发送功能:json
@Configuration
@EnableWebSocketMessageBroker//开启消息代理
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
/** * 创建链接点信息 * @param registry */
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws/ep").withSockJS();
registry.setApplicationDestinationPrefixes("/app");
}
/** * 配置消息队列 * 基于内存的STOMP消息代理 * @param registry */
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue");
}
}
复制代码
- 将 "/ws/ep" 注册为一个 STOMP 端点。客户端在订阅或发布消息到目的地路径前,要链接到该端点
- 以 /app 开头的消息都会被路由到带有@MessageMapping 或 @SubscribeMapping 注解的方法中;
- 以 /queue 开头的消息都会发送到STOMP代理中,根据所选择的STOMP代理不一样,目的地的可选前缀也会有所限制;
- 以/user开头的消息会将消息重路由到某个用户独有的目的地上。
自定义通讯协议websocket
@Controller
public class WScontroller {
@Autowired//消息发送模板
SimpMessagingTemplate simpMessagingTemplate;
@MessageMapping("/ws/chat")
public void receiveMessage(String message, Principal principal) {
String[] split = message.split(";");
HashMap<String, Object> map = new HashMap<>();
map.put("username",split[1]);
map.put("msg",split[0]);
simpMessagingTemplate.convertAndSendToUser(split[1], "/queue/msg",map);
}
复制代码
- 接收客户端发来的消息,参数就是消息自己
message
- @MessageMapping 或者 @SubscribeMapping 注解能够处理客户端发送过来的消息,并选择方法是否有返回值。
- @MessageMapping 指定目的地是“/app/ws/chat”(“/app”前缀是隐含的,由于咱们将其配置为应用的目的地前缀)。
- 通讯协议能够自定义——可自定义参数的格式
- 能够接收json格式的数据,传递josn数据时不须要添加额外注解@Requestbody
- 消息发送者不是从前端传递过来的,而是从springsecurity中获取的,防止前端冒充
- 若是 @MessageMapping 注解的控制器方法有返回值的话,返回值会被发送到消息代理,只不过会添加上"/topic"前缀。
- 经过为方法添加@SendTo注解,重载目的地
客户端代码(UVE)app
<template>
<div>
<div>
<div v-for="(m,index) in ms">{{m.username}}:{{m.msg}}</div>
</div>
<el-input v-model="msg"></el-input>
<el-button @click="sendMsg"></el-button>
</div>
</template>
<script>
import "../../lib/sockjs"
import "../../lib/stomp"
export default {
name: "FriendChat",
data() {
return {
msg: '',
ms: [],
stomp: null
};
},
mounted() {
this.intCon();
},
methods: {
// 创建链接
initCon() {
let _this = this;
this.stomp = Stomp.over(new SockJS("/ws/ep"));
this.stomp.connect({},success=>{
_this.stomp.subscribe("/user/queue/msg",msg=>{
_this.ms.push(JSON.parse(msg.body));
})
},fail=>{
})
},
// 发送消息
sendMsg() {
this.stomp.send("/ws/chat",{},this.msg)
}
}
}
</script>
<style scoped>
</style>
复制代码