本文只出示部分重要代码:
- 如何传递Long类型消息
- 如何传递对象类型消息-见github中
解码
public class ByteToLongDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//因为 long 8个字节, 需要判断有8个字节,才能读取一个long
if (in.readableBytes() >= 8) {
out.add(in.readLong());
}
}
}
编码
public class LongToByteEncoder extends MessageToByteEncoder<Long> {
@Override
protected void encode(ChannelHandlerContext ctx, Long msg, ByteBuf out) throws Exception {
out.writeLong(msg);
}
}
详细代码:Github