Spring Springboot实现websocket通讯-2

特别说明:1. 本文基于Springboot spring-boot-starter-parent 1.5.1.RELEASE编码,在不同的版本中部分方法有区别。2. 因为博客字数限制,拆分成了两篇文章


第一篇地址:Spring Springboot实现websocket通讯-1
第二篇地址:Spring Springboot实现websocket通讯-2



前面两种建立websocket通讯,不管是用javax的包还是spring的包都是用的比较底层的协议,下面我们来看看用上层的STOMP来建立websocket通讯

SockJs+Spring-WebSocket时,由于SockJs与Spring WebSocket之间采用JSON通讯,需要引入jackson 2的相关jar包

<code>         
        
            com.fasterxml.jackson.core
            jackson-core
            2.6.3
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.6.3
        
        
            com.fasterxml.jackson.core
            jackson-annotations
            2.6.3
        /<code>

前面已经提到了STOMP是一个上层协议,STOMP 在 WebSocket 之上提供了一个基于 帧的线路格式层,用来定义消息语义。STOMP 帧:该帧由命令,一个或多个 头信息 以及 负载所组成。如下就是发送 数据的一个 STOMP帧:

<code>SEND
destination:/app/marco
content-length:20
 
{"message":"hello word!"}/<code>
  • SEND:STOMP命令,表明会发送一些内容;
  • destination:头信息,用来表示消息发送到哪里;
  • content-length:头信息,用来表示 负载内容的 大小;
  • 空行:
  • 帧内容(负载)内容
  • 要使用STOMP 通讯,服务端,和客户端都必须支持,服务端的准备步骤

    服务端准备工作

    1. 我们已经配置了STOMP通讯的配置类 WebSocketStompConfig
    2. 配置了WebSocketChannelInterceptor 和 WebSocketHandshakeInterceptor 两个自定义拦截器
    3. 一个WebSocketStompController 用于接收客户端消息和响应客户端
    4. 一个简单的MVC controller 用于跳转websocket 页面

    在Spring中启用STOMP通讯不用我们自己去写原生态的帧,spring的消息功能是基于代理模式构建,其实说得复杂,都是封装好了的,如果需要开启SOMP,只需要在websocket配置类上使用@EnableWebSocketMessageBroker (注解的作用为能够在 WebSocket 上启用 STOMP),并实现WebSocketMessageBrokerConfigurer接口,有些教程在这一步会继承AbstractWebSocketMessageBrokerConfigurer 类,我们看一下AbstractWebSocketMessageBrokerConfigurer类的源码,可以看到都是空方法,也是实现的接口,这里推荐自己实现接口,因为官方API上AbstractWebSocketMessageBrokerConfigurer已经标记为废弃

    Spring Springboot实现websocket通讯-2

    AbstractWebSocketMessageBrokerConfigurer 抽象类

    <code>public abstract class AbstractWebSocketMessageBrokerConfigurer implements WebSocketMessageBrokerConfigurer {
        public AbstractWebSocketMessageBrokerConfigurer() {
        }
    
        public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
        }
    
        public void configureClientInboundChannel(ChannelRegistration registration) {
        }
    
        public void configureClientOutboundChannel(ChannelRegistration registration) {
        }
    
        public boolean configureMessageConverters(List messageConverters) {
            return true;
        }
    
        public void addArgumentResolvers(List argumentResolvers) {
        }
    
        public void addReturnValueHandlers(List/<code>


    分享到:


    相關文章: