SpringBoot實現(xiàn)WebSocket服務(wù)并讓客戶端實時接收
在 Spring Boot 中實現(xiàn) WebSocket 服務(wù)并讓客戶端實時接收消息,可以使用 Spring Boot 內(nèi)置的 WebSocket 支持。下面我為你提供一個基于 Spring Boot 和 WebSocket 的完整 Demo。
1. 引入依賴
首先,在 pom.xml
中添加 WebSocket 的依賴:
<dependencies> <!-- WebSocket 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> </dependencies>
2. WebSocket 配置
創(chuàng)建一個配置類 WebSocketConfig.java
,用于配置 WebSocket 的端點和處理邏輯。
import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { // 注冊 WebSocket 處理器和端點 registry.addHandler(new WebSocketHandler(), "/websocket") .setAllowedOrigins("*"); // 允許跨域 } }
3. WebSocket 處理器
創(chuàng)建 WebSocketHandler.java
,處理 WebSocket 的連接、消息接收、消息廣播等操作。
import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.util.HashSet; import java.util.Set; public class WebSocketHandler extends TextWebSocketHandler { // 用于保存所有連接的 WebSocket 會話 private static final Set<WebSocketSession> sessions = new HashSet<>(); // 當(dāng)有客戶端連接時調(diào)用 @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); session.sendMessage(new TextMessage("歡迎連接 WebSocket 服務(wù)器!")); } // 當(dāng)有消息從客戶端發(fā)送過來時調(diào)用 @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { System.out.println("收到客戶端消息: " + message.getPayload()); } // 當(dāng)連接關(guān)閉時調(diào)用 @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } // 廣播消息給所有連接的客戶端 public static void broadcast(String message) throws Exception { for (WebSocketSession session : sessions) { if (session.isOpen()) { session.sendMessage(new TextMessage(message)); } } } }
4. 模擬公告推送
創(chuàng)建一個控制器 AnnouncementController.java
,模擬公告的發(fā)布功能。發(fā)布公告時,會調(diào)用 WebSocket 處理器的 broadcast
方法,將消息推送給所有已連接的客戶端。
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class AnnouncementController { @GetMapping("/announce") public String sendAnnouncement() { try { // 模擬公告內(nèi)容 String announcement = "新公告發(fā)布于: " + System.currentTimeMillis(); WebSocketHandler.broadcast(announcement); return "公告已發(fā)布: " + announcement; } catch (Exception e) { e.printStackTrace(); return "發(fā)布失敗"; } } }
5. 運行步驟
1. 啟動 Spring Boot 應(yīng)用
啟動 Spring Boot 項目后,WebSocket 服務(wù)器將會在 /websocket
端點上監(jiān)聽。
2. 小程序或網(wǎng)頁客戶端
客戶端可以是小程序或者網(wǎng)頁。這里提供一個簡單的 HTML 客戶端來測試 WebSocket 連接。
HTML 客戶端代碼(用于測試 WebSocket 連接):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Demo</title> </head> <body> <h1>WebSocket Demo</h1> <div id="messages"></div> <script> // 連接 WebSocket 服務(wù)器 var socket = new WebSocket("ws://localhost:8080/websocket"); socket.onopen = function() { console.log("連接成功!"); }; socket.onmessage = function(event) { console.log("收到消息:", event.data); document.getElementById("messages").innerHTML += "<p>" + event.data + "</p>"; }; socket.onclose = function() { console.log("連接關(guān)閉!"); }; </script> </body> </html>
3. 發(fā)布公告
使用瀏覽器訪問 http://localhost:8080/announce
,每次訪問該地址時,服務(wù)器會推送一條公告消息給所有連接的 WebSocket 客戶端。
6. 小程序端實現(xiàn)
你也可以在微信小程序中使用類似的方式,通過 WebSocket 接收服務(wù)器推送的公告。
Page({ data: { messages: [] // 保存接收到的公告消息 }, onLoad: function() { // 連接 WebSocket 服務(wù)器 wx.connectSocket({ url: 'ws://localhost:8080/websocket', // 注意修改為你的服務(wù)器地址 success: (res) => { console.log('WebSocket 連接成功!'); }, fail: (err) => { console.error('WebSocket 連接失敗', err); } }); // 監(jiān)聽 WebSocket 消息 wx.onSocketMessage((res) => { console.log('收到服務(wù)器消息:', res.data); this.setData({ messages: [...this.data.messages, res.data] // 將新消息添加到列表中 }); }); // 監(jiān)聽 WebSocket 連接關(guān)閉 wx.onSocketClose((res) => { console.log('WebSocket 已關(guān)閉', res); }); } });
7. 總結(jié)
- 通過 Spring Boot 的 WebSocket 支持,可以在服務(wù)器端推送實時公告。
- 客戶端可以是 HTML 頁面,也可以是微信小程序,使用 WebSocket 接口接收公告消息。
到此這篇關(guān)于SpringBoot實現(xiàn)WebSocket服務(wù)并讓客戶端實時接收的文章就介紹到這了,更多相關(guān)SpringBoot WebSocket實時接收內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java發(fā)送HttpClient請求及接收請求結(jié)果過程的簡單實例
下面小編就為大家?guī)硪黄猨ava發(fā)送HttpClient請求及接收請求結(jié)果過程的簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11SpringBoot 簽到獎勵實現(xiàn)方案的示例代碼
這篇文章主要介紹了SpringBoot 簽到獎勵實現(xiàn)方案的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08