要使用WebSocket,您需要在Spring Boot项目中添加以下依赖项:
1. Maven依赖项:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2. Gradle依赖项:
implementation 'org.springframework.boot:spring-boot-starter-websocket'
接下来,您需要编写WebSocket处理程序和配置类。
1. 创建一个WebSocket处理程序:
import org.springframework.stereotype.Component; import org.springframework.web.socket.handler.AbstractWebSocketHandler; @Component public class MyWebSocketHandler extends AbstractWebSocketHandler { @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { // 处理收到的文本消息 String payload = message.getPayload(); // ... } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { // 当WebSocket连接建立时执行的操作 // ... } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // 当WebSocket连接关闭时执行的操作 // ... } }
2. 创建一个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 { private final MyWebSocketHandler webSocketHandler; public WebSocketConfig(MyWebSocketHandler webSocketHandler) { this.webSocketHandler = webSocketHandler; } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(webSocketHandler, "/websocket").setAllowedOrigins("*"); } }
在这个配置类中,我们将WebSocket处理程序注册为"/websocket"路径的处理程序,并允许所有来源的连接。
这样,您就可以使用WebSocket了。您可以在控制器中注入`MyWebSocketHandler`并使用它来处理WebSocket连接。