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.java
REST的架构是经过不少URL去实现的web
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请求架构
须要上层的子协议去解析进来的消息app
This is comparable to how most web applications today are written using a web framework rather than the Servlet API alone.less
STOMP (Spring支持)async
定义进来的消息怎么处理ide
Provides methods for configuring WebSocketHandler request mappings.ui
这个接口只有一个方法:code
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))); } }
它竟然不是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(); }