|
14 | 14 |
|
15 | 15 | public class ToMessageDecoder extends ByteToMessageDecoder { |
16 | 16 |
|
17 | | - private static final Logger log = LoggerFactory |
18 | | - .getLogger(ToMessageDecoder.class); |
19 | | - |
20 | 17 | @Override |
21 | | - protected void decode(ChannelHandlerContext arg0, ByteBuf arg1, |
22 | | - List<Object> arg2) throws Exception { |
| 18 | + protected void decode(ChannelHandlerContext ctx, ByteBuf in, |
| 19 | + List<Object> out) throws Exception { |
23 | 20 |
|
24 | 21 | // At least 5 bytes to decode |
25 | | - if (arg1.readableBytes() >= 5) { |
26 | | - int msgLength = arg1.readInt(); |
27 | | - byte msgType = arg1.readByte(); |
28 | | - if (msgLength >= 5) { |
29 | | - ByteBuf bf = arg1.readBytes(msgLength - 5); |
30 | | - byte[] data = bf.array(); |
31 | | - Header header = new Header(); |
32 | | - header.setMsgLength(msgLength); |
33 | | - header.setMsgType(msgType); |
34 | | - |
35 | | - Message message = new Message(); |
36 | | - message.setHeader(header); |
37 | | - message.setData(data); |
38 | | - |
39 | | - arg2.add(message); // Decode one message successfully |
40 | | - } |
| 22 | + if (in.readableBytes() < 5) { |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + in.markReaderIndex(); |
| 27 | + |
| 28 | + int msgLength = in.readInt(); |
| 29 | + if (in.readableBytes() < msgLength) { |
| 30 | + in.resetReaderIndex(); |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + byte msgType = in.readByte(); |
| 35 | + if (msgLength >= 5) { |
| 36 | + ByteBuf bf = in.readBytes(msgLength - 5); |
| 37 | + byte[] data = bf.array(); |
| 38 | + Header header = new Header(); |
| 39 | + header.setMsgLength(msgLength); |
| 40 | + header.setMsgType(msgType); |
| 41 | + |
| 42 | + Message message = new Message(); |
| 43 | + message.setHeader(header); |
| 44 | + message.setData(data); |
| 45 | + |
| 46 | + out.add(message); // Decode one message successfully |
41 | 47 | } |
42 | | - } |
43 | | - |
44 | | - @Override |
45 | | - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) |
46 | | - throws Exception { |
47 | | - ctx.close(); |
48 | | - log.error(cause.getMessage()); |
49 | 48 | } |
50 | 49 | } |
0 commit comments