Spring Boot WebSocket入门示例

作者:da吃一鲸8862024.01.30 00:07浏览量:71

简介:本文将通过一个简单的示例,介绍如何在Spring Boot项目中设置和使用WebSocket。我们将从设置WebSocket的依赖开始,创建一个WebSocket端点,以及实现简单的WebSocket通信。

在Spring Boot项目中集成WebSocket非常简单。下面是一个基本的WebSocket入门示例,展示了如何在Spring Boot应用中设置和使用WebSocket。
1. 添加WebSocket依赖
首先,你需要在你的pom.xml文件中添加Spring Boot的WebSocket依赖。确保你的pom.xml中包含以下内容:

  1. <dependencies>
  2. <!-- 其他依赖项 -->
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-websocket</artifactId>
  6. </dependency>
  7. </dependencies>

2. 配置WebSocket
application.propertiesapplication.yml文件中,添加以下配置:

  1. # application.properties
  2. spring.websocket.enabled=true

或者在application.yml中:

  1. spring:
  2. websocket:
  3. enabled: true

3. 创建WebSocket端点
接下来,创建一个处理WebSocket连接的端点。创建一个名为EchoController的Java类:

  1. import org.springframework.web.socket.TextMessage;
  2. import org.springframework.web.socket.WebSocketSession;
  3. import org.springframework.web.socket.handler.TextWebSocketHandler;
  4. public class EchoController extends TextWebSocketHandler {
  5. @Override
  6. public void handleTextMessage(WebSocketSession session, TextMessage message) {
  7. // 当收到文本消息时,将消息回传给客户端。
  8. session.sendMessage(message);
  9. }
  10. }

4. 注册WebSocket端点
在你的Spring Boot应用中注册EchoController。如果你使用的是Spring Boot的自动配置功能,那么在启动应用时,Spring将会自动检测到你的控制器并注册它。否则,你需要在配置类中手动注册它:

  1. import org.springframework.context.annotation.Configuration;
  2. import org.springframework.web.socket.config.annotation.EnableWebSocket;
  3. import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
  4. import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
  5. import org.springframework.web.socket.handler.TextWebSocketHandler;
  6. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  7. import org.springframework.context.annotation.Bean;
  8. import java.util.Collections;
  9. import java.util.Set;
  10. import java.util.*;
  11. import javax.websocket.*;
  12. import javax.websocket.server.*;
  13. import org.springframework.*;
  14. import org.springframework.beans.*;
  15. import org.springframework.context.*;
  16. import org.springframework.core.*;
  17. import org.springframework.util.*;