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((byte) 0x00));
36 private static final ByteBuf _0XFF = Unpooled.unreleasableBuffer(
37 Unpooled.directBuffer(1, 1).writeByte((byte) 0xFF));
38 private static final ByteBuf _0XFF_0X00 = Unpooled.unreleasableBuffer(
39 Unpooled.directBuffer(2, 2).writeByte((byte) 0xFF).writeByte((byte) 0x00));
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(b4);
74 } else {
75 buf.writeByte(b3 | 0x80);
76 buf.writeByte(b4);
77 }
78 } else {
79 buf.writeByte(b2 | 0x80);
80 buf.writeByte(b3 | 0x80);
81 buf.writeByte(b4);
82 }
83 } else {
84 buf.writeByte(b1 | 0x80);
85 buf.writeByte(b2 | 0x80);
86 buf.writeByte(b3 | 0x80);
87 buf.writeByte(b4);
88 }
89
90
91 out.add(buf);
92 out.add(data.retain());
93 release = false;
94 } finally {
95 if (release) {
96 buf.release();
97 }
98 }
99 }
100 }
101 }