1. 程式人生 > >Spring Boot之WebSocket

Spring Boot之WebSocket

package 說明 clas return pre tell ebs 異常 override

一、項目說明

1、項目地址:https://github.com/hqzmss/test01-springboot-websocket.git

2、IDE:IntelliJ IDEA 2018.1.1 x64

二、步驟說明

Spring Boot實現WebSocket比較簡單,主要分以下四步:

1、添加依賴

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-websocket</artifactId>
4 </dependency>

其他的依賴只涉及到Spring Boot本身的依賴

2、創建攔截器

攔截器要實現【HandshakeInterceptor】這個接口,並實現它的兩個方法。

攔截器的主要作用是在WebSocket創建握手之前和之後進行一些相應的處理

 1 package com.hqzmss.websocket_demo1;
 2 
 3 import org.springframework.http.server.ServerHttpRequest;
 4 import org.springframework.http.server.ServerHttpResponse;
5 import org.springframework.web.socket.WebSocketHandler; 6 import org.springframework.web.socket.server.HandshakeInterceptor; 7 8 import java.util.Map; 9 10 /** 11 * 攔截器 12 */ 13 public class MyWebSocketInterceptor implements HandshakeInterceptor { 14 15 /** 16 * 握手之前調用 17 * @param
serverHttpRequest 當前請求 18 * @param serverHttpResponse 當前響應 19 * @param webSocketHandler 目標處理器 20 * @param map 請求屬性 21 * @return 是否通過 22 * @throws Exception 異常信息 23 */ 24 @Override 25 public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception { 26 System.out.println("連接前進行處理"); 27 return true; 28 } 29 30 /** 31 * 握手之後調用 32 * @param serverHttpRequest 當前請求 33 * @param serverHttpResponse 當前響應 34 * @param webSocketHandler 目標處理器 35 * @param e 握手期間引發的異常,如果沒有,則為null 36 */ 37 @Override 38 public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) { 39 System.out.println("連接後進行處理"); 40 } 41 } 42

3、創建處理器

處理器是所有消息的處理中心。

【afterConnectionEstablished】:這個方法會為每個WebSocket連接創建一個WebSocketSession,標識一個連接。

              可以將這個WebSocketSession保存起來,以後要是服務器有消息要發送到這個客戶端,則通過WebSocketSession直接發送

【handleMessage】:從客戶端發來的消息由此方法接收並做相應處理。消息由WebSocketMessage來接收。

 1 package com.hqzmss.websocket_demo1;
 2 
 3 import org.springframework.web.socket.*;
 4 
 5 /**
 6  * 創建處理器
 7  */
 8 public class MyHandler implements WebSocketHandler  {
 9     /**
10      * 在WebSocket協商成功後調用,並且打開WebSocket連接準備使用
11      * @param webSocketSession webSocketSession
12      * @throws Exception 異常
13      */
14     @Override
15     public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
16         System.out.println("sessionId=" + webSocketSession.getId());
17     }
18 
19     /**
20      * 當一個新的WebSocket消息到達時調用
21      * @param webSocketSession webSocketSession
22      * @param webSocketMessage webSocketMessage
23      * @throws Exception 異常
24      */
25     @Override
26     public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
27         System.out.println(webSocketMessage.getPayload());
28         System.out.println("有消息到達服務器!");
29     }
30 
31     /**
32      * 處理來自底層WebSocket消息傳輸的錯誤
33      * @param webSocketSession webSocketSession
34      * @param throwable 錯誤
35      * @throws Exception 異常
36      */
37     @Override
38     public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
39 
40     }
41 
42     /**
43      * 在網絡套接字連接關閉後或在傳輸錯誤發生後調用。
44      * 盡管從技術上講,會話可能仍然是開放的,但取決於底層實現,在這一點上發送消息是不鼓勵的,而且很可能不會成功。
45      * @param webSocketSession webSocketSession
46      * @param closeStatus closeStatus
47      * @throws Exception 異常
48      */
49     @Override
50     public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
51         if(webSocketSession.isOpen()) {
52             webSocketSession.close();
53         }
54         System.out.println("安全退出了系統");
55     }
56 
57     /**
58      * WebSocketHandler是否處理部分消息
59      * @return 標誌
60      */
61     @Override
62     public boolean supportsPartialMessages() {
63         return false;
64     }
65 }

4、添加配置項目

1)、要記得添加@EnableWebSocket註解,標識這個配置是WebSocket配置

2)、"/webSocketServer.action"是自定義的連接點,客戶端要通過WebSocket連接此服務器則是通過此連接點

3)、.setAllowedOrigins("*"),這個方法要加上,不加的話有可能連接會被攔截掉

 1 package com.hqzmss.websocket_demo1;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.web.socket.WebSocketHandler;
 6 import org.springframework.web.socket.config.annotation.*;
 7 
 8 @Configuration
 9 @EnableWebSocket
10 public class WebSocketConfig implements  WebSocketConfigurer {
11 
12     @Override
13     public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
14         webSocketHandlerRegistry.addHandler(webSocketHandler(), "/webSocketServer.action").addInterceptors(new MyWebSocketInterceptor()).setAllowedOrigins("*");
15         webSocketHandlerRegistry.addHandler(webSocketHandler(), "/sockjs/webSocketServer.action")
16                 .addInterceptors(new MyWebSocketInterceptor()).withSockJS();
17     }
18 
19     @Bean
20     public WebSocketHandler webSocketHandler() {
21         return new MyHandler();
22     }
23 }

Spring Boot之WebSocket