在Spring Boot中使用WebSocket可以通過以下步驟實現:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
}
}
@Component
public class WebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 處理收到的消息
String payload = message.getPayload();
session.sendMessage(new TextMessage("收到消息:" + payload));
}
}
var socket = new WebSocket("ws://localhost:8080/ws");
socket.onopen = function() {
console.log("連接成功");
};
socket.onmessage = function(event) {
console.log("收到消息:" + event.data);
};
socket.send("Hello, WebSocket!");
以上就是在Spring Boot中使用WebSocket的基本步驟,通過WebSocket可以實現實時通信和消息推送功能。