I. Description of the project
1. Project Address: Https://github.com/hqzmss/test01-springboot-websocket.git
2. Ide:intellij Idea 2018.1.1 x64
Ii. Description of the steps
The Spring boot implementation WebSocket is relatively simple and consists of the following four steps:
1. Add dependencies
1 < dependency > 2 < GroupId > org.springframework.boot </ groupid > 3 < artifactid Span style= "COLOR: #0000ff" >> spring-boot-starter-websocket</ Span style= "COLOR: #800000" >artifactid > 4 </ Dependency >
Other dependencies only involve the dependency of spring boot itself
2. Creating interceptors
The Interceptor implements the "Handshakeinterceptor" interface and implements its two methods.
The main function of interceptors is to perform some corresponding processing before and after WebSocket creates a handshake
1 PackageCom.hqzmss.websocket_demo1;2 3 Importorg.springframework.http.server.ServerHttpRequest;4 ImportOrg.springframework.http.server.ServerHttpResponse;5 ImportOrg.springframework.web.socket.WebSocketHandler;6 ImportOrg.springframework.web.socket.server.HandshakeInterceptor;7 8 ImportJava.util.Map;9 Ten /** One * interception Device A */ - Public classMywebsocketinterceptorImplementsHandshakeinterceptor { - the /** - * Call before shaking hands - * @paramserverhttprequest Current request - * @paramServerhttpresponse Current Response + * @paramWebsockethandler Target Processor - * @paramMap Request Properties + * @returnwhether to pass A * @throwsException Exception Information at */ - @Override - Public BooleanBeforehandshake (ServerHTTPRequest serverhttprequest, Serverhttpresponse serverhttpresponse, WebSocketHandler Websockethandler, map<string, object> Map)throwsException { -SYSTEM.OUT.PRINTLN ("process before connecting"); - return true; - } in - /** to * Call after handshake + * @paramserverhttprequest Current request - * @paramServerhttpresponse Current Response the * @paramWebsockethandler Target Processor * * @paramThe exception that is thrown during the e-handshake, or null if not $ */Panax Notoginseng @Override - Public voidAfterhandshake (serverhttprequest serverhttprequest, Serverhttpresponse serverhttpresponse, WebSocketHandler Websockethandler, Exception e) { theSYSTEM.OUT.PRINTLN ("Process after connection"); + } A } the
3. Create the processor
The processor is the processing center for all messages.
"Afterconnectionestablished": This method creates a websocketsession for each websocket connection, identifying a connection.
This websocketsession can be saved, and if the server has a message to be sent to this client, it is sent directly via Websocketsession.
"Handlemessage": Messages sent from the client are received by this method and processed accordingly. The message is received by Websocketmessage.
1 PackageCom.hqzmss.websocket_demo1;2 3 Importorg.springframework.web.socket.*;4 5 /**6 * Create processor7 */8 Public classMyHandlerImplementsWebsockethandler {9 /**Ten * Called after websocket negotiation is successful and open WebSocket connection ready to use One * @paramwebsocketsession websocketsession A * @throwsException Exception - */ - @Override the Public voidAfterconnectionestablished (websocketsession websocketsession)throwsException { -System.out.println ("sessionid=" +Websocketsession.getid ()); - } - + /** - * Called when a new WebSocket message arrives + * @paramwebsocketsession websocketsession A * @paramwebsocketmessage websocketmessage at * @throwsException Exception - */ - @Override - Public voidHandlemessage (websocketsession websocketsession, websocketmessage<?> websocketmessage)throwsException { - System.out.println (Websocketmessage.getpayload ()); -SYSTEM.OUT.PRINTLN ("a message arrives at the server!") "); in } - to /** + * Handling errors from the underlying WebSocket message transmission - * @paramwebsocketsession websocketsession the * @paramthrowable Error * * @throwsException Exception $ */Panax Notoginseng @Override - Public voidHandletransporterror (websocketsession websocketsession, Throwable throwable)throwsException { the + } A the /** + * Called after a network socket connection has been closed or after a transmission error has occurred. - * Although the session may still be open, depending on the underlying implementation, sending the message at this point is discouraged and probably will not succeed. $ * @paramwebsocketsession websocketsession $ * @paramclosestatus Closestatus - * @throwsException Exception - */ the @Override - Public voidAfterconnectionclosed (websocketsession websocketsession, Closestatus closestatus)throwsException {Wuyi if(Websocketsession.isopen ()) { the websocketsession.close (); - } WuSystem.out.println ("Safely exited the system"); - } About $ /** - * Websockethandler whether to handle partial messages - * @returnlogo - */ A @Override + Public Booleansupportspartialmessages () { the return false; - } $}
4. Adding Configuration Items
1), to remember to add @enablewebsocket annotations, identify this configuration is WebSocket configuration
2), "/websocketserver.action" is a custom connection point, the client to connect to this server through WebSocket is through this connection point
3),. Setallowedorigins ("*"), this method must be added, if not added, it is possible that the connection will be intercepted.
1 PackageCom.hqzmss.websocket_demo1;2 3 ImportOrg.springframework.context.annotation.Bean;4 Importorg.springframework.context.annotation.Configuration;5 ImportOrg.springframework.web.socket.WebSocketHandler;6 Importorg.springframework.web.socket.config.annotation.*;7 8 @Configuration9 @EnableWebSocketTen Public classWebsocketconfigImplementsWebsocketconfigurer { One A @Override - Public voidregisterwebsockethandlers (Websockethandlerregistry websockethandlerregistry) { -Websockethandlerregistry.addhandler (Websockethandler (), "/websocketserver.action"). Addinterceptors (NewMywebsocketinterceptor ()). Setallowedorigins ("*"); theWebsockethandlerregistry.addhandler (Websockethandler (), "/sockjs/websocketserver.action") -. Addinterceptors (NewMywebsocketinterceptor ()). WITHSOCKJS (); - } - + @Bean - PublicWebsockethandler Websockethandler () { + return NewMyHandler (); A } at}
Spring Boot's WebSocket