How to use WebSocket in Spring Boot?
WebSocket can be implemented in Spring Boot by following these steps:
- First, add the WebSocket dependency:
Add the following dependency in the pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- Create a WebSocket configuration class:
Set up a class specifically for configuring WebSocket-related parameters and handlers. You can refer to the following example for guidance.
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
}
}
- Create a WebSocket handler:
Develop a WebSocket handler class for handling events and messages related to WebSocket connections. You can refer to the following example for guidance.
@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));
}
}
- Create a WebSocket client:
Use JavaScript to establish a WebSocket connection, send and receive messages on the front-end webpage. Refer to the following example:
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!");
- Run the application:
Start the Spring Boot application, access the front-end page, and test the WebSocket connection and message transmission functionality.
These are the basic steps to use WebSocket in Spring Boot, which allows for real-time communication and message push functionality.