SpringBoot 整合 WebSocket 實現前後端訊息互傳
什麼是WebSocket?
WebSocket 協議是基於 TCP 的一種新的網路協議。它實現了瀏覽器與伺服器全雙工 (full-duplex) 通訊—允許伺服器主動傳送資訊給客戶端。
為什麼需要WebSocket?
大家都知道以前客戶端想知道服務端的處理進度,要不停地使用 Ajax 進行輪詢,讓瀏覽器隔個幾秒就向伺服器發一次請求,這對伺服器壓力較大。另外一種輪詢就是採用 long poll 的方式,這就跟打電話差不多,沒收到訊息就一直不掛電話,也就是說,客戶端發起連線後,如果沒訊息,就一直不返回 response 給客戶端,連線階段一直是阻塞的。
而 WebSocket 解決了 HTTP 的這幾個難題。當伺服器完成協議升級後( HTTP -> WebSocket ),服務端可以主動推送資訊給客戶端,解決了輪詢造成的同步延遲問題。由於 WebSocket 只需要一次 HTTP 握手,服務端就能一直與客戶端保持通訊,直到關閉連線,這樣就解決了伺服器需要反覆解析 HTTP 協議,減少了資源的開銷。
現在通過 SpringBoot 整合 WebSocket 來實現前後端通訊。
整合 WebSocket 實現前後端通訊
專案程式碼結構圖
依賴匯入
SpringBoot2.0 對 WebSocket 的支援簡直太棒了,直接就有包可以引入 。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
複製程式碼
配置 WebSocketConfig
啟用WebSocket的支援也是很簡單,將ServerEndpointExporter物件注入到容器中。
package com.tuhu.websocketsample.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
複製程式碼
WebSocket 服務端 WebSocketServer
因為 WebSocket 是類似客戶端服務端的形式(採用ws協議),那麼這裡的 WebSocketServer 其實就相當於一個 ws協議的 Controller。直接 @ServerEndpoint("/websocket") 、@Component 啟用即可,然後在裡面實現@OnOpen,@onClose,@onMessage等方法
package com.tuhu.websocketsample.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/websocket/{sid}")
@Slf4j
public class WebSocketServer {
/**
* 靜態變數,用來記錄當前線上連線數。應該把它設計成執行緒安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包的執行緒安全Set,用來存放每個客戶端對應的MyWebSocket物件。
*/
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
/**
* 與某個客戶端的連線會話,需要通過它來給客戶端傳送資料
*/
private Session session;
/**
* 接收sid
*/
private String sid="";
/**
* 連線建立成功呼叫的方法
**/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
//加入set中
webSocketSet.add(this);
//線上數加1
addOnlineCount();
log.info("有新視窗開始監聽:"+sid+",當前線上人數為" + getOnlineCount());
this.sid=sid;
try {
sendMessage("連線成功");
} catch (IOException e) {
log.error("websocket IO異常");
}
}
/**
* 連線關閉呼叫的方法
*/
@OnClose
public void onClose() {
//從set中刪除
webSocketSet.remove(this);
//線上數減1
subOnlineCount();
log.info("有一連線關閉!當前線上人數為" + getOnlineCount());
}
/**
* 收到客戶端訊息後呼叫的方法
* @param message 客戶端傳送過來的訊息
**/
@OnMessage
public void onMessage(String message,Session session) {
log.info("收到來自視窗"+sid+"的資訊:"+message);
//群發訊息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session,Throwable error) {
log.error("發生錯誤");
error.printStackTrace();
}
/**
* 實現伺服器主動推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群發自定義訊息
* */
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送訊息到視窗"+sid+",推送內容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//這裡可以設定只推送給這個sid的,為null則全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
複製程式碼
訊息推送
至於推送新資訊,可以再自己的 Controller 寫個方法呼叫 WebSocketServer.sendInfo() 即可
package com.tuhu.websocketsample.controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
@RestController
@RequestMapping("/checkcenter")
public class CheckCenterController {
/**
* 頁面請求
* @param cid
* @return
*/
@GetMapping("/socket/{cid}")
public ModelAndView socket(@PathVariable String cid) {
ModelAndView mav=new ModelAndView("/socket");
mav.addObject("cid",cid);
return mav;
}
/**
* 推送資料介面
* @param cid
* @param message
* @return
*/
@ResponseBody
@RequestMapping("/socket/push/{cid}")
public String pushToWeb(@PathVariable String cid,String message) {
try {
WebSocketServer.sendInfo(message,cid);
} catch (IOException e) {
e.printStackTrace();
return "error:"+cid+"#"+e.getMessage();
}
return "success:"+cid;
}
}
複製程式碼
頁面發起socket請求
然後在頁面用js程式碼呼叫 socket,當然,太古老的瀏覽器是不行的,一般新的瀏覽器或者谷歌瀏覽器是沒問題的。還有一點,記得協議是ws的哦。直接在瀏覽器控制檯開啟連線。
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的瀏覽器不支援WebSocket");
}else{
console.log("您的瀏覽器支援WebSocket");
//實現化WebSocket物件,指定要連線的伺服器地址與埠 建立連線
socket = new WebSocket("ws://localhost:8080/websocket/20");
//開啟事件
socket.onopen = function() {
console.log("Socket 已開啟");
//socket.send("這是來自客戶端的訊息" + location.href + new Date());
};
//獲得訊息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//發現訊息進入 開始處理前端觸發邏輯
};
//關閉事件
socket.onclose = function() {
console.log("Socket已關閉");
};
//發生了錯誤事件
socket.onerror = function() {
alert("Socket發生了錯誤");
//此時可以嘗試重新整理頁面
}
//離開頁面時,關閉socket
//jquery1.8中已經被廢棄,3.0中已經移除
// $(window).unload(function(){
// socket.close();
//});
}
複製程式碼
執行效果
現在可以在瀏覽器開啟連線,通過客戶端呼叫介面服務端就可以向瀏覽器傳送訊息。
現在開啟兩個頁面開啟兩個連線:
- socket = new WebSocket("ws://localhost:8080/websocket/20") ;
- socket = new WebSocket("ws://localhost:8080/websocket/22") ;
向前端推送資料:
- http://localhost:8080/checkcenter/socket/push/20?message=Hello
- http://localhost:8080/checkcenter/socket/push/22?message=HelloWorld
可以看到服務端已經將訊息推送給了客戶端
而客戶端也收到了訊息
先開啟頁面,指定cid,啟用socket接收,然後再另一個頁面呼叫剛才Controller封裝的推送資訊的方法到這個cid的socket,即可向前端推送訊息。
後續
serverEndpointExporter 錯誤
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘serverEndpointExporter’ defined in class path resource [com/xxx/WebSocketConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: javax.websocket.server.ServerContainer not available
如果 tomcat 部署一直報這個錯,請移除 WebSocketConfig 中 @Bean ServerEndpointExporter 的注入 。
ServerEndpointExporter 是由 Spring 官方提供的標準實現,用於掃描 ServerEndpointConfig 配置類和@ServerEndpoint 註解例項。使用規則也很簡單:
1、如果使用預設的嵌入式容器 比如Tomcat 則必須手工在上下文提供ServerEndpointExporter。
2、如果使用外部容器部署war包,則不需要提供提供ServerEndpointExporter,因為此時SpringBoot預設將掃描 服務端的行為交給外部容器處理,所以線上部署的時候要把WebSocketConfig中這段注入bean的程式碼注掉。