Spring Boot 下 WebSocket 使用

Spring Boot WebSocket 工具模块 (Spring Boot WebSocket Utils)

这个工具模块为Spring Boot应用程序提供了一种优雅的方式,使用注解来处理WebSocket端点,与Java EE中的@ServerEndpoint相似。

This utility module provides an elegant way to handle WebSocket endpoints in Spring Boot applications by using annotations, similar to the @ServerEndpoint in Java EE.

功能 (Features)

  • 基于注解的WebSocket端点 (Annotation-based WebSocket Endpoint): 使用@WebSocketMapping注解声明WebSocket端点。

  • 自动配置 (Automatic Configuration): 一旦在项目中包含了此模块并满足必要的条件,WebSocket配置将自动设置。

使用要求 (Requirements)

  • Java 8 或更高版本 (Java 8 or higher)

  • 带有spring-boot-starter-websocket依赖的Spring Boot

开始使用 (Getting Started)

1. 添加依赖 (Add Dependency)

Step 1. Add the JitPack repository to your build file

<repositories>
<repository>
   <id>jitpack.io</id>
   <url>https://jitpack.io</url>
</repository>
</repositories>

Step 2. Add the dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
 

<dependency>
   <groupId>com.github.Wiggle</groupId>
   <artifactId>spring-boot-starter-websocket-utils</artifactId>
   <version>1.0.4</version>
</dependency>

2. 创建WebSocket处理器 (Create WebSocket Handler)

通过继承TextWebSocketHandler并使用@WebSocketMapping注解来指定端点,创建一个处理器。

Create a handler by extending TextWebSocketHandler and use the @WebSocketMapping annotation to specify the endpoint.

javaCopy code
import org.wiggle.websocket.annotation.WebSocketMapping;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
​
@WebSocketMapping("/my-websocket-endpoint")
public class MyWebSocketHandler extends TextWebSocketHandler {
  @Override
  public void handleTextMessage(WebSocketSession session, TextMessage message) {
      // 你的处理逻辑 (Your handling logic)
  }
}

3. 运行你的Spring Boot应用程序 (Run Your Spring Boot Application)

运行你的Spring Boot应用程序后,WebSocket端点将在/my-websocket-endpoint处可用。

Once you run your Spring Boot application, the WebSocket endpoint will be available at /my-websocket-endpoint.

程序源码

GitHub - Wiggle/spring-boot-starter-websocket-utils

开源不易,感谢 来主页支持!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值