使用場景:
當前端調用WebSocket時,後臺從第三方接口獲取數據,實時推送到前端(每隔5秒)。
一、什麼是WebSocket?
WebSocket協議是基於TCP的一種新的網絡協議。它實現了瀏覽器與服務器全雙工(full-duplex)通信——允許服務器主動發送信息給客戶端。
二、爲什麼需要 WebSocket ?
初次接觸 WebSocket 的人,都會問同樣的問題:我們已經有了 HTTP 協議,爲什麼還需要另一個協議?他能帶來什麼好處?
答案很簡單,因爲 HTTP 協議有一個缺陷:通信只能由客戶端發起
。
舉例來說,我們想了解今天的天氣,只能是客戶端向服務器發出請求,服務器返回查詢結果。HTTP 協議做不到服務器主動向客戶端推送信息。
這種單向請求的特點,註定瞭如果服務器有連續的狀態變化,客戶端要獲知就非常麻煩。我們只能使用"輪詢":每隔一段時候,就發出一個詢問,瞭解服務器有沒有新的信息。最典型的場景就是聊天室
。
輪詢的效率低,非常浪費資源(因爲必須不停連接,或者 HTTP 連接始終打開)。因此,工程師們一直在思考,有沒有更好的方法。WebSocket 就是這樣發明的。
三、WebSocket 簡介
WebSocket 協議在2008年誕生,2011年成爲國際標準。所有瀏覽器都已經支持了。
它的最大特點就是,服務器可以主動向客戶端推送信息,客戶端也可以主動向服務器發送信息,是真正的雙向平等對話,屬於服務器推送技術的一種。
其他特點包括:
(1)建立在 TCP 協議之上,服務器端的實現比較容易。
(2)與 HTTP 協議有着良好的兼容性。默認端口也是80和443,並且握手階段採用 HTTP 協議,因此握手時不容易屏蔽,能通過各種 HTTP 代理服務器。
(3)數據格式比較輕量,性能開銷小,通信高效。
(4)可以發送文本,也可以發送二進制數據。
(5)沒有同源限制,客戶端可以與任意服務器通信。
(6)協議標識符是 ws
(如果加密,則爲 wss
),服務器網址就是 URL。
ws://127.0.0.1:80/ws/path
四、代碼實現
4.1 maven 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
因涉及到 js 連接服務端,這裏也寫了調用 WebSocket 的 html,此處集成了 thymeleaf 模板。【前後分離的項目可省略,此處都是前端的工作。】
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置文件:
server:
port: 8082
#添加Thymeleaf配置
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
content-type: text/html
4.2 啓動 WebSocket 支持
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 開啓 WebSocket 支持
* @author Siona
* @date 2020/4/8 17:40
**/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
4.3 自定義 WebSocketServer
WebSocket 的核心代碼。
(1)WebSocket 是類似客戶端服務端的形式(採用 ws 協議),此處的 WebSocketServer相當於一個 ws
協議的 Controller。
(2)實現 @OnOpen
開啓連接,@onClose
關閉連接,@onMessage
接收消息等方法。
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shingis.common.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Siona
* @date 2020/4/8 17:43
**/
@Slf4j
@ServerEndpoint("/ws/{userId}")
@Component
public class WebSocketServer {
/**
* 靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的
*/
private static int onlineCount = 0;
/**
* concurrent 包的線程安全Set,用來存放每個客戶端對應的 myWebSocket對象
* 根據userId來獲取對應的 WebSocket
*/
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**
* 與某個客戶端的連接會話,需要通過它來給客戶端發送數據
*/
private Session session;
/**
* 接收 sid
*/
private String userId = "";
/**
* 連接建立成功調用的方法
*
* @param session
* @param userId
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
webSocketMap.put(userId, this);
log.info("webSocketMap -> " + JSON.toJSONString(webSocketMap));
addOnlineCount(); // 在線數 +1
log.info("有新窗口開始監聽:" + userId + ",當前在線人數爲" + getOnlineCount());
try {
sendMessage(JSON.toJSONString("連接成功"));
} catch (IOException e) {
e.printStackTrace();
throw new ApiException("websocket IO異常!!!!");
}
}
/**
* 關閉連接
*/
@OnClose
public void onClose() {
if (webSocketMap.get(this.userId) != null) {
webSocketMap.remove(this.userId);
subOnlineCount(); // 人數 -1
log.info("有一連接關閉,當前在線人數爲:" + getOnlineCount());
}
}
/**
* 收到客戶端消息後調用的方法
*
* @param message 客戶端發送過來的消息
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到來自窗口" + userId + "的信息:" + message);
if (StringUtils.isNotBlank(message)) {
try {
// 解析發送的報文
JSONObject jsonObject = JSON.parseObject(message);
// 追加發送人(防竄改)
jsonObject.put("fromUserId", this.userId);
String toUserId = jsonObject.getString("toUserId");
// 傳送給對應 toUserId 用戶的 WebSocket
if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
} else {
log.info("請求的userId:" + toUserId + "不在該服務器上"); // 否則不在這個服務器上,發送到 MySQL 或者 Redis
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用戶錯誤:" + this.userId + ",原因:" + error.getMessage());
error.printStackTrace();
}
/**
* 實現服務器主動推送
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 羣發自定義消息
*
* @param message
* @param userId
* @throws IOException
*/
public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
// 遍歷集合,可設置爲推送給指定sid,爲 null 時發送給所有人
Iterator entrys = webSocketMap.entrySet().iterator();
while (entrys.hasNext()) {
Map.Entry entry = (Map.Entry) entrys.next();
if (userId == null) {
webSocketMap.get(entry.getKey()).sendMessage(message);
log.info("發送消息到:" + entry.getKey() + ",消息:" + message);
} else if (entry.getKey().equals(userId)) {
webSocketMap.get(entry.getKey()).sendMessage(message);
log.info("發送消息到:" + entry.getKey() + ",消息:" + message);
}
}
}
private static synchronized int getOnlineCount() {
return onlineCount;
}
private static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
private static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
4.4 實時消息推送
此處需求是 項目啓動就會自動推送到前端,前端開啓 WebSocket 後進行接收。
調用兩個第三方接口的數據 同時推送給前端,如果是前端點擊不同的頁面或按鈕只需要一個接口的數據,則改爲使用兩個 WebSocket 分別推送即可。
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @author Siona
* @date 2020/4/9 10:12
**/
@Slf4j
@Component // 被Spring容器管理
@Order(1) // 如果多個自定義ApplicationRunner,用來表明執行順序
public class PushAlarm implements ApplicationRunner { // 服務啓動後自動加載該類
@Autowired
GasSupport gasSupport;
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("------------->" + "項目啓動,now =" + new Date());
this.myTimer();
}
public void myTimer() {
String userId = null; // userId 爲空時,會推送給連接此 WebSocket 的所有人
Runnable runnable1 = new Runnable() {
@SneakyThrows
@Override
public void run() {
while (true) {
String message = gasSupport.GetWasteGasRealData(""); // 第三方接口返回數據
WebSocketServer.sendInfo(message, userId); // 推送
Thread.sleep(5000);
}
}
};
Runnable runnable2 = new Runnable() {
@SneakyThrows
@Override
public void run() {
while (true) {
String message = gasSupport.GetWasteWaterRealData(""); // 第三方接口返回數據
WebSocketServer.sendInfo(message, userId); // 推送
Thread.sleep(5000);
}
}
};
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
thread1.start();
thread2.start();
}
}
4.5 前端頁面
頁面用 js 代碼 調用 WebSocket
,最新的瀏覽器一般都支持(我用的谷歌瀏覽器)。最重要的一點就是使用 ws
協議,如果使用了一些路徑類,可以用 replace("http","ws")
來替換。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>websocket通訊</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
var socket;
function openSocket() {
if(typeof(WebSocket) == "undefined") {
console.log("您的瀏覽器不支持WebSocket");
}else{
console.log("您的瀏覽器支持WebSocket");
//實現化WebSocket對象,指定要連接的服務器地址與端口 建立連接
//等同於socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
//var socketUrl="${request.contextPath}/im/"+$("#userId").val();
var socketUrl="http://localhost:5001/ws/"+$("#userId").val();
socketUrl=socketUrl.replace("https","ws").replace("http","ws");
console.log(socketUrl);
if(socket!=null){
socket.close();
socket=null;
}
socket = new WebSocket(socketUrl);
//打開事件
socket.onopen = function() {
console.log("websocket已打開");
//socket.send("這是來自客戶端的消息" + location.href + new Date());
};
//獲得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//發現消息進入 開始處理前端觸發邏輯
};
//關閉事件
socket.onclose = function() {
console.log("websocket已關閉");
};
//發生了錯誤事件
socket.onerror = function() {
console.log("websocket發生了錯誤");
}
}
}
function sendMessage() {
if(typeof(WebSocket) == "undefined") {
console.log("您的瀏覽器不支持WebSocket");
}else {
console.log("您的瀏覽器支持WebSocket");
console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
}
}
</script>
<body>
<p>【userId】:<div><input id="userId" name="userId" type="text" value="10"></div>
<p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="20"></div>
<p>【toUserId】:<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】:<div><a onclick="openSocket()">開啓socket</a></div>
<p>【操作】:<div><a onclick="sendMessage()">發送消息</a></div>
</body>
</html>
4.6 編寫 Controller 類
跳轉到指定頁面(webSocket.html)
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Siona
* @date 2020/4/8 18:40
**/
@RestController
public class DemoController {
@GetMapping("/index")
public ResponseEntity<String> index() {
return ResponseEntity.ok("請求成功");
}
@GetMapping("/page")
public ModelAndView page() {
return new ModelAndView("webSocket");
}
}
4.7 運行
瀏覽器輸入 http://localhost:5001/page
,打開 webSocket.html 頁面,F12 打開控制檯查看測試結果。
開啓socket後,可以看到控制檯出現服務端不斷推送的數據。
小結
ConcurrentHashMap:保證多線程安全,同時方便利用 map.get(userId)
進行推送到指定窗口。
相比Set,Set遍歷是費事且麻煩的事情,而Map的get是簡單便捷的,當WebSocket數量大的時候,這個小小的消耗就會聚少成多,影響體驗,所以需要優化。在IM的場景下,指定userId進行推送消息更加方便。