spring-boot-and-websocket

create@2017-10-10

spring boot集成websocket. 由于现实当中网络环境复杂,b/s之间的层层代理某些可能不支持websocket,所以使用兼容性强的sockjs,当遇到不支持的情况时,降级为streaming,long polling等模式。

server端

老套路,在spring boot工程里引入对应的包, 添加配置代码.


// websocket
compile('org.springframework.boot:spring-boot-starter-websocket')
	

package net.skycloud.nap.common.websocket;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

/**
 * Created by work on 2017/9/29.
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic", "/queue");
        config.setApplicationDestinationPrefixes("/nap");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/endpoint").setAllowedOrigins("*").withSockJS();
    }
}
	

浏览器端

测试页面很简单,先引入sockjs和stomp, stomp是对协议封装后的高级API. 之后订阅公共频道和自己的频道即可.


<!DOCTYPE HTML>
<html>
   <head>
       <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>

      <script type="text/javascript">
         function WebSocketTest() {
             var socket = new SockJS('http://192.168.0.181:8081/api/endpoint');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/notifications/event', function (notification) {
                    console.log(notification);
                });
                stompClient.subscribe('/queue/notifications/admin', function (notification) {
                    console.log(notification);
                });
            });
         }
      </script>
   </head>
   <body>
      <div id="sse">
         <a href="javascript:WebSocketTest()">Run WebSocket</a>
      </div>
   </body>
</html>