SpringBoot整合websocket實現後端向頁面傳送訊息
阿新 • • 發佈:2020-12-31
1、引入依賴:
compile "org.springframework.boot:spring-boot-starter-web:${verSpringBoot}"
compile "org.springframework.boot:spring-boot-starter-websocket:${verSpringBoot}"
2、新增Webscoket配置:
/** * ServerEndpointExporter 作用 * * 這個Bean會自動註冊使用@ServerEndpoint註解宣告的websocket endpoint * *@return */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }
3、後端程式碼:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.ConcurrentHashMap; @Component @ServerEndpoint("/websocket/{id}") public class WebSocketServer { public Logger log = LoggerFactory.getLogger(getClass()); /** * 客戶端ID */ privateString id = ""; /** * 與某個客戶端的連線會話,需要通過它來給客戶端傳送資料 */ private Session session; /** * 記錄當前線上連線數(為保證執行緒安全,須對使用此變數的方法加lock或synchronized) */ private static int onlineCount = 0; /** * 用來儲存當前線上的客戶端(此map執行緒安全) */ private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>(); /** * 連線建立成功後呼叫 */ @OnOpen public void onOpen(@PathParam(value = "id") String id, Session session) { this.session = session; // 接收到傳送訊息的客戶端編號 this.id = id; // 加入map中 webSocketMap.put(id, this); // 線上數加1 addOnlineCount(); log.info("客戶端" + id + "加入,當前線上數為:" + getOnlineCount()); try { sendMessage("WebSocket連線成功"); } catch (IOException e) { log.error("WebSocket IO異常"); } } /** * 連線關閉時呼叫 */ @OnClose public void onClose() { // 從map中刪除 webSocketMap.remove(this.id); // 線上數減1 subOnlineCount(); log.info("有一連線關閉,當前線上數為:" + getOnlineCount()); } /** * 收到客戶端訊息後呼叫 * @param message 客戶端傳送過來的訊息<br/> * 訊息格式:內容 - 表示群發,內容|X - 表示發給id為X的客戶端 * @param session 使用者資訊 */ @OnMessage public void onMessage(String message, Session session) { log.info("來自客戶端的訊息:" + message); String[] messages = message.split("[|]"); try { if (messages.length > 1) { sendToUser(messages[0], messages[1]); } else { sendToAll(messages[0]); } } catch (IOException e) { log.error(e.getMessage(), e); } } /** * 發生錯誤時回撥 * * @param session 使用者資訊 * @param error 錯誤 */ @OnError public void onError(Session session, Throwable error) { log.error("WebSocket發生錯誤"); error.printStackTrace(); } /** * 推送資訊給指定ID客戶端,如客戶端不線上,則返回不線上資訊給自己 * * @param message 客戶端發來的訊息 * @param sendClientId 客戶端ID */ public void sendToUser(String message, String sendClientId) throws IOException { if (webSocketMap.get(sendClientId) != null) { if (!id.equals(sendClientId)) { webSocketMap.get(sendClientId) .sendMessage("客戶端" + id + "發來訊息:" + " <br/> " + message); } else { webSocketMap.get(sendClientId).sendMessage(message); } } else { // 如客戶端不線上,則返回不線上資訊給自己 sendToUser("當前客戶端不線上", id); } } public static void sendToWeb(String message, String sendClientId) throws IOException { if (webSocketMap.get(sendClientId) != null) { webSocketMap.get(sendClientId).sendMessage(message); } else { // 如客戶端不線上,則返回不線上資訊給自己 System.out.println(sendClientId + "=當前客戶端不線上"); } } /** * 群送傳送資訊給所有人 * * @param message 要傳送的訊息 */ public void sendToAll(String message) throws IOException { for (String key : webSocketMap.keySet()) { webSocketMap.get(key).sendMessage(message); } } /** * 傳送訊息 * @param message 要傳送的訊息 */ private void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 獲取線上人數 * @return 線上人數 */ private static synchronized int getOnlineCount() { return onlineCount; } /** * 有人上線時線上人數加一 */ private static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } /** * 有人下線時線上人數減一 */ private static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } }
4、前端程式碼:
<!DOCTYPE HTML> <html> <head> <title>My WebSocket</title> </head> <body> <input id="text" type="text" /> <button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button> <div id="message"></div> </body> <script type="text/javascript"> var websocket = null; //判斷當前瀏覽器是否支援WebSocket, 主要此處要更換為自己的地址 if ('WebSocket' in window) { websocket = new WebSocket("ws://127.0.0.1:16666/ts/websocket/1"); } else { alert('Not support websocket') } //連線發生錯誤的回撥方法 websocket.onerror = function() { setMessageInnerHTML("error"); }; //連線成功建立的回撥方法 websocket.onopen = function(event) { setMessageInnerHTML("open"); } //接收到訊息的回撥方法 websocket.onmessage = function(event) { setMessageInnerHTML(event.data); } //連線關閉的回撥方法 websocket.onclose = function() { setMessageInnerHTML("close"); } //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket連線,防止連線還沒斷開就關閉視窗,server端會拋異常。 window.onbeforeunload = function() { websocket.close(); } //將訊息顯示在網頁上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //關閉連線 function closeWebSocket() { websocket.close(); } //傳送訊息 function send() { var message = document.getElementById('text').value; websocket.send(message); } </script> </html>
5、測試程式碼:
@RequestMapping(value="/sendMessage/{clientId}",method = {RequestMethod.GET}) public void sendTest(@PathVariable String clientId) throws Throwable{ WebSocketServer.sendToWeb("你有一個新任務"+System.currentTimeMillis(), clientId); }