Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 1 | package org.onlab.netty; |
| 2 | |
| 3 | import io.netty.buffer.ByteBuf; |
| 4 | import io.netty.channel.ChannelHandlerContext; |
| 5 | import io.netty.handler.codec.MessageToByteEncoder; |
| 6 | |
| 7 | /** |
| 8 | * Encode InternalMessage out into a byte buffer. |
| 9 | */ |
| 10 | public class MessageEncoder extends MessageToByteEncoder<InternalMessage> { |
| 11 | |
| 12 | // onosiscool in ascii |
| 13 | public static final byte[] PREAMBLE = "onosiscool".getBytes(); |
| 14 | |
| 15 | private final Serializer serializer; |
| 16 | |
| 17 | public MessageEncoder(Serializer serializer) { |
| 18 | this.serializer = serializer; |
| 19 | } |
| 20 | |
| 21 | @Override |
| 22 | protected void encode(ChannelHandlerContext context, InternalMessage message, |
| 23 | ByteBuf out) throws Exception { |
| 24 | |
| 25 | // write preamble |
| 26 | out.writeBytes(PREAMBLE); |
| 27 | |
| 28 | // write id |
| 29 | out.writeLong(message.id()); |
| 30 | |
| 31 | // write type length |
| 32 | out.writeInt(message.type().length()); |
| 33 | |
| 34 | // write type |
| 35 | out.writeBytes(message.type().getBytes()); |
| 36 | |
| 37 | // write sender host name size |
| 38 | out.writeInt(message.sender().host().length()); |
| 39 | |
| 40 | // write sender host name. |
| 41 | out.writeBytes(message.sender().host().getBytes()); |
| 42 | |
| 43 | // write port |
| 44 | out.writeInt(message.sender().port()); |
| 45 | |
| 46 | try { |
| 47 | serializer.encode(message.payload()); |
| 48 | } catch (Exception e) { |
| 49 | e.printStackTrace(); |
| 50 | } |
| 51 | |
| 52 | byte[] payload = serializer.encode(message.payload()); |
| 53 | |
| 54 | // write payload length. |
| 55 | out.writeInt(payload.length); |
| 56 | |
| 57 | // write payload bytes |
| 58 | out.writeBytes(payload); |
| 59 | } |
| 60 | } |