【WebSocket】SpringBoot项目中使用WebSocket
1. 导入坐标
如果springboot父工程没有加入websocket的起步依赖,添加它的坐标的时候需要带上版本号。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. 创建WebSocketServer服务类
【豆包】
@ServerEndpoint注解
- 声明服务器端点:通过在类上添加
@ServerEndpoint
注解,该类就成为了一个 WebSocket 服务器端点,可以接收客户端的连接。- 指定访问路径:注解的
value
属性用于指定客户端连接的 URI 路径,例如@ServerEndpoint("/ws")
表示客户端可以通过ws://服务器地址/ws
连接到该端点。- 和@PathParam注解配合使用
@PathParam注解
- 动态路径匹配:通过在
@ServerEndpoint
的路径中定义参数占位符(如/{username}
),可以捕获客户端连接 URI 中的实际值。- 参数注入:将捕获的路径参数值注入到
@OnOpen
、@OnMessage
或@OnClose
注解方法的参数中。- 类型转换:自动将路径参数从字符串转换为基本数据类型(如
int
、long
、boolean
等)。@OnOpen注解
- 连接初始化:在客户端与服务器成功建立 WebSocket 连接后,被
@OnOpen
注解标记的方法会立即执行。- 参数注入:方法可以接收特定参数,如
Session
对象、连接参数等。@OnMessage
- 自动解码:配合
Decoder
使用时,可以自动将消息转换为自定义对象。- 异步响应:支持同步或异步发送响应。
@OnClose
- 资源释放:清理连接相关的资源(如会话数据、数据库连接)。
- 通知其他客户端:广播用户离开的消息。
- 获取关闭状态:通过
CloseReason
参数了解关闭原因。
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {//存放会话对象private static Map<String, Session> sessionMap = new HashMap();//连接建立成功调用的方法@OnOpenpublic void onOpen(Session session, @PathParam("sid") String sid) {System.out.println("客户端:" + sid + "建立连接");sessionMap.put(sid, session);}//收到客户端消息后调用的方法@OnMessagepublic void onMessage(String message, @PathParam("sid") String sid) {System.out.println("收到来自客户端:" + sid + "的信息:" + message);}//连接关闭调用的方法@OnClosepublic void onClose(@PathParam("sid") String sid) {System.out.println("连接断开:" + sid);sessionMap.remove(sid);}//主动发送消息 (群发消息)public void sendToAllClient(String message) {Collection<Session> sessions = sessionMap.values();for (Session session : sessions) {try {//服务器向客户端发送消息session.getBasicRemote().sendText(message);System.out.println("发送websocket");} catch (Exception e) {e.printStackTrace();}}}}
3. 将WebSocket配置成bean
@Configuration
public class WebSocketConfiguration {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}