1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.codec.http.websocketx;
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 @Sharable
34 public class WebSocket00FrameEncoder extends OneToOneEncoder {
35
36 @Override
37 protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
38 if (msg instanceof WebSocketFrame) {
39 WebSocketFrame frame = (WebSocketFrame) msg;
40 if (frame instanceof TextWebSocketFrame) {
41
42 ChannelBuffer data = frame.getBinaryData();
43 ChannelBuffer encoded = channel.getConfig().getBufferFactory()
44 .getBuffer(data.order(), data.readableBytes() + 2);
45 encoded.writeByte((byte) 0x00);
46 encoded.writeBytes(data, data.readerIndex(), data.readableBytes());
47 encoded.writeByte((byte) 0xFF);
48 return encoded;
49 } else if (frame instanceof CloseWebSocketFrame) {
50
51 ChannelBuffer data = frame.getBinaryData();
52 ChannelBuffer encoded = channel.getConfig().getBufferFactory().getBuffer(data.order(), 2);
53 encoded.writeByte((byte) 0xFF);
54 encoded.writeByte((byte) 0x00);
55 return encoded;
56 } else {
57
58 ChannelBuffer data = frame.getBinaryData();
59 int dataLen = data.readableBytes();
60 ChannelBuffer encoded = channel.getConfig().getBufferFactory().getBuffer(data.order(), dataLen + 5);
61
62
63 encoded.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 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 }