Spring with WebSocket

消息架构

Today REST is a widely accepted, understood, and supported architecture for building web applications. It is an architecture that relies on having many URLs (nouns), a handful of HTTP methods (verbs), and other principles such as using hypermedia (links), remaining stateless, etc.

REST的架构是通过很多URL去实现的

By contrast a WebSocket application may use a single URL only for the initial HTTP handshake. All messages thereafter share and flow on the same TCP connection. This points to an entirely different, asynchronous, event-driven, messaging architecture. One that is much closer to traditional messaging applications (e.g. JMS, AMQP).

WebSocket的握手却只需要一次HTTP请求

子协议

需要上层的子协议去解析进来的消息

This is comparable to how most web applications today are written using a web framework rather than the Servlet API alone.

STOMP (Spring支持)

Spring里头关于WebSocket几个重要的概念

WebSocketHandler

定义进来的消息怎么处理

WebSocketConfigurer

Provides methods for configuring WebSocketHandler request mappings.

这个接口只有一个方法:

addHandler(WebSocketHandler webSocketHandler, java.lang.String… paths)

Configure a WebSocketHandler at the specified URL paths.

建立连接

要在服务器端准备好WebSocket Engine

根据具体的服务器不一样办法也不一样,因为WebSocket是http的Upgrade协议,所以需要UpgradeStrategy也不难理解

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(echoWebSocketHandler(),
            "/echo").setHandshakeHandler(handshakeHandler()).withSocketJS();
    }

    @Bean
    public DefaultHandshakeHandler handshakeHandler() {

        WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
        policy.setInputBufferSize(8192);
        policy.setIdleTimeout(600000);

        return new DefaultHandshakeHandler(
                new JettyRequestUpgradeStrategy(new WebSocketServerFactory(policy)));
    }

}

WebSocketMessageBrokerConfigurer

它居然不是WebSocketConfigurer的子类。。。

两个方法:
configureMessageBroker 服务器开放的端口让客户端监听,也就是说写的时候往这里写

@Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.setApplicationDestinationPrefixes("/app");
        config.enableSimpleBroker("/queue", "/topic");
    }

registerStompEndpoints 服务器要监听的端口,message会从这里进来,要对这里加一个Handler

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

你可能感兴趣的:(spring,websocket)