简介:本文将通过一个简单的示例,介绍如何在Spring Boot项目中设置和使用WebSocket。我们将从设置WebSocket的依赖开始,创建一个WebSocket端点,以及实现简单的WebSocket通信。
在Spring Boot项目中集成WebSocket非常简单。下面是一个基本的WebSocket入门示例,展示了如何在Spring Boot应用中设置和使用WebSocket。
1. 添加WebSocket依赖
首先,你需要在你的pom.xml文件中添加Spring Boot的WebSocket依赖。确保你的pom.xml中包含以下内容:
<dependencies><!-- 其他依赖项 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency></dependencies>
2. 配置WebSocket
在application.properties或application.yml文件中,添加以下配置:
# application.propertiesspring.websocket.enabled=true
或者在application.yml中:
spring:websocket:enabled: true
3. 创建WebSocket端点
接下来,创建一个处理WebSocket连接的端点。创建一个名为EchoController的Java类:
import org.springframework.web.socket.TextMessage;import org.springframework.web.socket.WebSocketSession;import org.springframework.web.socket.handler.TextWebSocketHandler;public class EchoController extends TextWebSocketHandler {@Overridepublic void handleTextMessage(WebSocketSession session, TextMessage message) {// 当收到文本消息时,将消息回传给客户端。session.sendMessage(message);}}
4. 注册WebSocket端点
在你的Spring Boot应用中注册EchoController。如果你使用的是Spring Boot的自动配置功能,那么在启动应用时,Spring将会自动检测到你的控制器并注册它。否则,你需要在配置类中手动注册它:
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;import org.springframework.web.socket.handler.TextWebSocketHandler;import org.springframework.web.socket.server.standard.ServerEndpointExporter;import org.springframework.context.annotation.Bean;import java.util.Collections;import java.util.Set;import java.util.*;import javax.websocket.*;import javax.websocket.server.*;import org.springframework.*;import org.springframework.beans.*;import org.springframework.context.*;import org.springframework.core.*;import org.springframework.util.*;