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(); }