1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.serialization;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.ByteBufOutputStream;
20 import io.netty.channel.ChannelHandler.Sharable;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.handler.codec.MessageToByteEncoder;
23
24 import java.io.ObjectInputStream;
25 import java.io.ObjectOutputStream;
26 import java.io.Serializable;
27
28
29
30
31
32
33
34
35
36 @Sharable
37 public class ObjectEncoder extends MessageToByteEncoder<Serializable> {
38 private static final byte[] LENGTH_PLACEHOLDER = new byte[4];
39
40 @Override
41 protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
42 int startIdx = out.writerIndex();
43
44 ByteBufOutputStream bout = new ByteBufOutputStream(out);
45 ObjectOutputStream oout = null;
46 try {
47 bout.write(LENGTH_PLACEHOLDER);
48 oout = new CompactObjectOutputStream(bout);
49 oout.writeObject(msg);
50 oout.flush();
51 } finally {
52 if (oout != null) {
53 oout.close();
54 } else {
55 bout.close();
56 }
57 }
58
59 int endIdx = out.writerIndex();
60
61 out.setInt(startIdx, endIdx - startIdx - 4);
62 }
63 }