1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.http.websocketx;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.Unpooled;
20 import io.netty.channel.ChannelHandler.Sharable;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.handler.codec.MessageToMessageEncoder;
23
24 import java.util.List;
25
26
27
28
29
30
31
32 @Sharable
33 public class WebSocket00FrameEncoder extends MessageToMessageEncoder<WebSocketFrame> implements WebSocketFrameEncoder {
34 private static final ByteBuf _0X00 = Unpooled.unreleasableBuffer(
35 Unpooled.directBuffer(1, 1).writeByte(0x00)).asReadOnly();
36 private static final ByteBuf _0XFF = Unpooled.unreleasableBuffer(
37 Unpooled.directBuffer(1, 1).writeByte((byte) 0xFF)).asReadOnly();
38 private static final ByteBuf _0XFF_0X00 = Unpooled.unreleasableBuffer(
39 Unpooled.directBuffer(2, 2).writeByte((byte) 0xFF).writeByte(0x00)).asReadOnly();
40
41 @Override
42 protected void encode(ChannelHandlerContext ctx, WebSocketFrame msg, List<Object> out) throws Exception {
43 if (msg instanceof TextWebSocketFrame) {
44
45 ByteBuf data = msg.content();
46
47 out.add(_0X00.duplicate());
48 out.add(data.retain());
49 out.add(_0XFF.duplicate());
50 } else if (msg instanceof CloseWebSocketFrame) {
51
52
53 out.add(_0XFF_0X00.duplicate());
54 } else {
55
56 ByteBuf data = msg.content();
57 int dataLen = data.readableBytes();
58
59 ByteBuf buf = ctx.alloc().buffer(5);
60 boolean release = true;
61 try {
62
63 buf.writeByte((byte) 0x80);
64
65
66 int b1 = dataLen >>> 28 & 0x7F;
67 int b2 = dataLen >>> 14 & 0x7F;
68 int b3 = dataLen >>> 7 & 0x7F;
69 int b4 = dataLen & 0x7F;
70 if (b1 == 0) {
71 if (b2 == 0) {
72 if (b3 != 0) {
73 buf.writeByte(b3 | 0x80);
74 }
75 buf.writeByte(b4);
76 } else {
77 buf.writeByte(b2 | 0x80);
78 buf.writeByte(b3 | 0x80);
79 buf.writeByte(b4);
80 }
81 } else {
82 buf.writeByte(b1 | 0x80);
83 buf.writeByte(b2 | 0x80);
84 buf.writeByte(b3 | 0x80);
85 buf.writeByte(b4);
86 }
87
88
89 out.add(buf);
90 out.add(data.retain());
91 release = false;
92 } finally {
93 if (release) {
94 buf.release();
95 }
96 }
97 }
98 }
99 }