SpringBoot實(shí)現(xiàn)WebSocket服務(wù)并讓客戶端實(shí)時(shí)接收
在 Spring Boot 中實(shí)現(xiàn) WebSocket 服務(wù)并讓客戶端實(shí)時(shí)接收消息,可以使用 Spring Boot 內(nèi)置的 WebSocket 支持。下面我為你提供一個(gè)基于 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)建一個(gè)配置類 WebSocketConfig.java,用于配置 WebSocket 的端點(diǎn)和處理邏輯。
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) {
// 注冊(cè) WebSocket 處理器和端點(diǎn)
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 會(huì)話
private static final Set<WebSocketSession> sessions = new HashSet<>();
// 當(dāng)有客戶端連接時(shí)調(diào)用
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
session.sendMessage(new TextMessage("歡迎連接 WebSocket 服務(wù)器!"));
}
// 當(dāng)有消息從客戶端發(fā)送過來時(shí)調(diào)用
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
System.out.println("收到客戶端消息: " + message.getPayload());
}
// 當(dāng)連接關(guān)閉時(shí)調(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)建一個(gè)控制器 AnnouncementController.java,模擬公告的發(fā)布功能。發(fā)布公告時(shí),會(huì)調(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. 運(yùn)行步驟
1. 啟動(dòng) Spring Boot 應(yīng)用
啟動(dòng) Spring Boot 項(xiàng)目后,WebSocket 服務(wù)器將會(huì)在 /websocket 端點(diǎn)上監(jiān)聽。
2. 小程序或網(wǎng)頁(yè)客戶端
客戶端可以是小程序或者網(wǎng)頁(yè)。這里提供一個(gè)簡(jiǎn)單的 HTML 客戶端來測(cè)試 WebSocket 連接。
HTML 客戶端代碼(用于測(cè)試 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,每次訪問該地址時(shí),服務(wù)器會(huì)推送一條公告消息給所有連接的 WebSocket 客戶端。
6. 小程序端實(shí)現(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ù)器端推送實(shí)時(shí)公告。
- 客戶端可以是 HTML 頁(yè)面,也可以是微信小程序,使用 WebSocket 接口接收公告消息。
到此這篇關(guān)于SpringBoot實(shí)現(xiàn)WebSocket服務(wù)并讓客戶端實(shí)時(shí)接收的文章就介紹到這了,更多相關(guān)SpringBoot WebSocket實(shí)時(shí)接收內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用ResponseEntity作為的返回值的應(yīng)用
這篇文章主要介紹了使用ResponseEntity作為的返回值的應(yīng)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
Springboot微服務(wù)打包Docker鏡像流程解析
這篇文章主要介紹了Springboot微服務(wù)打包Docker鏡像流程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
Spring Cloud使用Feign進(jìn)行遠(yuǎn)程調(diào)用的操作指南
在idea中將java項(xiàng)目中的單個(gè)類打包成jar包操作
Java中自旋鎖與CAS機(jī)制的深層關(guān)系與區(qū)別

