1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.codec.http.websocket;
17
18 import org.jboss.netty.buffer.ChannelBuffer;
19 import org.jboss.netty.channel.Channel;
20 import org.jboss.netty.channel.ChannelHandler.Sharable;
21 import org.jboss.netty.channel.ChannelHandlerContext;
22 import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
23
24
25
26
27
28
29
30
31
32
33
34
35 @Deprecated
36 @Sharable
37 public class WebSocketFrameEncoder extends OneToOneEncoder {
38
39 @Override
40 protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
41 if (msg instanceof WebSocketFrame) {
42 WebSocketFrame frame = (WebSocketFrame) msg;
43 int type = frame.getType();
44 if (frame.isText()) {
45
46 ChannelBuffer data = frame.getBinaryData();
47 ChannelBuffer encoded =
48 channel.getConfig().getBufferFactory().getBuffer(
49 data.order(), data.readableBytes() + 2);
50 encoded.writeByte((byte) type);
51 encoded.writeBytes(data, data.readerIndex(), data.readableBytes());
52 encoded.writeByte((byte) 0xFF);
53 return encoded;
54 } else {
55
56 ChannelBuffer data = frame.getBinaryData();
57 int dataLen = data.readableBytes();
58 ChannelBuffer encoded =
59 channel.getConfig().getBufferFactory().getBuffer(
60 data.order(), dataLen + 5);
61
62
63 encoded.writeByte((byte) type);
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 encoded.writeByte(b4);
74 } else {
75 encoded.writeByte(b3 | 0x80);
76 encoded.writeByte(b4);
77 }
78 } else {
79 encoded.writeByte(b2 | 0x80);
80 encoded.writeByte(b3 | 0x80);
81 encoded.writeByte(b4);
82 }
83 } else {
84 encoded.writeByte(b1 | 0x80);
85 encoded.writeByte(b2 | 0x80);
86 encoded.writeByte(b3 | 0x80);
87 encoded.writeByte(b4);
88 }
89
90
91 encoded.writeBytes(data, data.readerIndex(), dataLen);
92 return encoded;
93 }
94 }
95 return msg;
96 }
97 }