dengzedong
2024-12-31 f1fe397df175a7ee809ea28530419116af84af28
提交 | 用户 | 时间
e7c126 1 package com.iailab.framework.websocket.core.session;
H 2
3 import org.springframework.web.socket.CloseStatus;
4 import org.springframework.web.socket.WebSocketHandler;
5 import org.springframework.web.socket.WebSocketSession;
6 import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;
7 import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
8
9 /**
10  * {@link WebSocketHandler} 的装饰类,实现了以下功能:
11  *
12  * 1. {@link WebSocketSession} 连接或关闭时,使用 {@link #sessionManager} 进行管理
13  * 2. 封装 {@link WebSocketSession} 支持并发操作
14  *
15  * @author iailab
16  */
17 public class WebSocketSessionHandlerDecorator extends WebSocketHandlerDecorator {
18
19     /**
20      * 发送时间的限制,单位:毫秒
21      */
22     private static final Integer SEND_TIME_LIMIT = 1000 * 5;
23     /**
24      * 发送消息缓冲上线,单位:bytes
25      */
26     private static final Integer BUFFER_SIZE_LIMIT = 1024 * 100;
27
28     private final WebSocketSessionManager sessionManager;
29
30     public WebSocketSessionHandlerDecorator(WebSocketHandler delegate,
31                                             WebSocketSessionManager sessionManager) {
32         super(delegate);
33         this.sessionManager = sessionManager;
34     }
35
36     @Override
37     public void afterConnectionEstablished(WebSocketSession session) {
38         // 实现 session 支持并发,可参考 https://blog.csdn.net/abu935009066/article/details/131218149
39         session = new ConcurrentWebSocketSessionDecorator(session, SEND_TIME_LIMIT, BUFFER_SIZE_LIMIT);
40         // 添加到 WebSocketSessionManager 中
41         sessionManager.addSession(session);
42     }
43
44     @Override
45     public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
46         sessionManager.removeSession(session);
47     }
48
49 }