4
4
import lombok .extern .slf4j .Slf4j ;
5
5
import org .wowtools .hppt .common .util .BytesUtil ;
6
6
7
+ import java .util .concurrent .BlockingQueue ;
8
+ import java .util .concurrent .LinkedBlockingQueue ;
9
+ import java .util .concurrent .TimeUnit ;
10
+
7
11
/**
8
12
* 客户端会话
9
13
*
14
18
public class ClientSession {
15
19
private final int sessionId ;
16
20
private final ChannelHandlerContext channelHandlerContext ;
17
- private final ClientSessionLifecycle lifecycle ;
21
+
22
+ private final BlockingQueue <byte []> sendToUserBytesQueue = new LinkedBlockingQueue <>();
23
+ private volatile boolean running = true ;
18
24
19
25
ClientSession (int sessionId , ChannelHandlerContext channelHandlerContext , ClientSessionLifecycle lifecycle ) {
20
26
this .sessionId = sessionId ;
21
27
this .channelHandlerContext = channelHandlerContext ;
22
- this .lifecycle = lifecycle ;
28
+ Thread .startVirtualThread (() -> {
29
+ while (running ) {
30
+ byte [] bytes ;
31
+ try {
32
+ bytes = sendToUserBytesQueue .poll (10 , TimeUnit .SECONDS );
33
+ } catch (InterruptedException e ) {
34
+ continue ;
35
+ }
36
+ if (null == bytes ) {
37
+ continue ;
38
+ }
39
+ bytes = lifecycle .beforeSendToUser (this , bytes );
40
+ if (null != bytes ) {
41
+ log .debug ("ClientSession {} 向用户发送字节 {}" , sessionId , bytes .length );
42
+ BytesUtil .writeToChannelHandlerContext (channelHandlerContext , bytes );
43
+ lifecycle .afterSendToUser (this , bytes );
44
+ }
45
+ }
46
+ log .debug ("ClientSession {} 接收线程结束" , sessionId );
47
+ });
23
48
}
24
49
25
50
/**
@@ -28,12 +53,7 @@ public class ClientSession {
28
53
* @param bytes bytes
29
54
*/
30
55
public void sendToUser (byte [] bytes ) {
31
- bytes = lifecycle .beforeSendToUser (this , bytes );
32
- if (null != bytes ) {
33
- log .debug ("ClientSession {} 向用户发送字节 {}" , sessionId , bytes .length );
34
- BytesUtil .writeToChannelHandlerContext (channelHandlerContext , bytes );
35
- lifecycle .afterSendToUser (this , bytes );
36
- }
56
+ sendToUserBytesQueue .add (bytes );
37
57
}
38
58
39
59
@@ -46,6 +66,7 @@ public ChannelHandlerContext getChannelHandlerContext() {
46
66
}
47
67
48
68
void close () {
69
+ running = false ;
49
70
channelHandlerContext .close ();
50
71
}
51
72
0 commit comments