下面是一個簡單的 Spring Boot WebSocket 範例:
1. 首先,在 pom.xml 中添加相關的依賴項:
```xml
<dependencies>
<!-- 其他依賴項 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
```
2. 創建一個 WebSocketHandler 來處理 WebSocket 連接:
```java
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
@Component
public class SimpleWebSocketHandler extends TextWebSocketHandler {
private static final List<WebSocketSession> sessions = new ArrayList<>();
/**
* 當連接建立時執行
*/
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
log.info("WebSocket Connection Established: " + session.getId());
}
/**
* 連接關閉時執行
*/
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
sessions.remove(session);
log.info("WebSocket Connection Closed: " + session.getId());
}
/**
* 錯誤處理
*/
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
log.error("Error on WebSocket connection: " + session.getId());
exception.printStackTrace();
}
/**
* 收到消息時執行
*/
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 接收客戶端傳來的 JSON 字符串
String jsonMessage = message.getPayload();
// 在此處對 JSON 字符串進行解析,處理你的邏輯
// 假設你有一個回覆訊息的 JSON 對象
String responseJson = "{\"message\": \"Hello from server!\"}";
// 將回覆訊息發送給客戶端
session.sendMessage(new TextMessage(responseJson));
}
}
```
3. 註冊 WebSocketHandler:
```java
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 {
private final SimpleWebSocketHandler simpleWebSocketHandler;
public WebSocketConfig(SimpleWebSocketHandler simpleWebSocketHandler) {
this.simpleWebSocketHandler = simpleWebSocketHandler;
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(simpleWebSocketHandler, "/ws").setAllowedOrigins("*");
}
}
```
4. 在您的控制器中建立一個 WebSocket 客戶端頁面:
```html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Client</title>
</head>
<body>
<h1>WebSocket Client</h1>
<div id="output"></div>
<script>
const socket = new WebSocket('ws://localhost:8080/ws');
socket.onopen = function(event) {
console.log('WebSocket Connection Opened');
// 向後端發送資料(假設資料是一個 JSON 物件)
const data = { message: 'Hello from client!' };
socket.send(JSON.stringify(data));
};
socket.onmessage = function(event) {
const outputDiv = document.getElementById('output');
const message = event.data;
outputDiv.innerHTML += '<p>' + message + '</p>';
};
socket.onclose = function(event) {
console.log('WebSocket Connection Closed');
};
</script>
</body>
</html>
```
5. 啟動您的 Spring Boot 應用程式並在瀏覽器中打開 WebSocket 客戶端頁面(http://localhost:8080/),您應該能夠看到 WebSocket Connection Established 的訊息,並收到 Hello from server! 的回覆。當您關閉網頁或中斷 WebSocket 連接時,應用程式會顯示 WebSocket Connection Closed 的訊息。
這個範例中,我們建立了一個 WebSocketHandler 來處理 WebSocket 連接,並將它註冊到 WebSocketConfigurer 中。然後,在 WebSocket 客戶端頁面中,我們使用 JavaScript 的 WebSocket 物件建立了一個 WebSocket 連接,並註冊了 onopen、onmessage 和 onclose 事件處理函式來處理 WebSocket 事件。