WebSocket 協議是基於 TCP 的一種新的網絡協議。它實現了瀏覽器與服務器全雙工 (full-duplex) 通訊—容許服務器主動發送信息給客戶端。前端
你們都知道之前客戶端想知道服務端的處理進度,要不停地使用 Ajax 進行輪詢,讓瀏覽器隔個幾秒就向服務器發一次請求,這對服務器壓力較大。另一種輪詢就是採用 long poll 的方式,這就跟打電話差很少,沒收到消息就一直不掛電話,也就是說,客戶端發起鏈接後,若是沒消息,就一直不返回 response 給客戶端,鏈接階段一直是阻塞的。java
而 WebSocket 解決了 HTTP 的這幾個難題。當服務器完成協議升級後( HTTP -> WebSocket ),服務端能夠主動推送信息給客戶端,解決了輪詢形成的同步延遲問題。因爲 WebSocket 只須要一次 HTTP 握手,服務端就能一直與客戶端保持通訊,直到關閉鏈接,這樣就解決了服務器須要反覆解析 HTTP 協議,減小了資源的開銷。jquery
如今經過 SpringBoot 集成 WebSocket 來實現先後端通訊。web
項目代碼結構圖 spring
SpringBoot2.0 對 WebSocket 的支持簡直太棒了,直接就有包能夠引入 。後端
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
複製代碼
啓用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 是相似客戶端服務端的形式(採用ws協議),那麼這裏的 WebSocketServer 其實就至關於一個 ws協議的 Controller。直接 @ServerEndpoint("/websocket") 、@Component 啓用便可,而後在裏面實現@OnOpen , @onClose ,@onMessage等方法tomcat
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;
}
}
複製代碼
而後在頁面用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();
//});
}
複製代碼
如今能夠在瀏覽器開啓鏈接,經過客戶端調用接口服務端就能夠向瀏覽器發送消息。
如今打開兩個頁面開啓兩個鏈接:
向前端推送數據:
能夠看到服務端已經將消息推送給了客戶端
而客戶端也收到了消息
先打開頁面,指定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 註解實例。使用規則也很簡單:
一、若是使用默認的嵌入式容器 好比Tomcat 則必須手工在上下文提供ServerEndpointExporter。
二、若是使用外部容器部署war包,則不須要提供提供ServerEndpointExporter,由於此時SpringBoot默認將掃描 服務端的行爲交給外部容器處理,因此線上部署的時候要把WebSocketConfig中這段注入bean的代碼注掉。