@ChannelHandler.Sharable public class ProtobufDecoderNano extends MessageToMessageDecoder<ByteBuf>
ByteBuf
解码为Google Protocol Buffers MessageNano
。
请注意,如果您正在使用基于流的传输(如TCP / IP),则必须将此解码器与ByteToMessageDecoder
(如LengthFieldBasedFrameDecoder
)一起使用。
TCP / IP的典型设置是:
ChannelPipeline
pipeline = ...;
// Decoders
pipeline.addLast("frameDecoder",
new LengthFieldBasedFrameDecoder
(1048576, 0, 4, 0, 4));
pipeline.addLast("protobufDecoder",
new ProtobufDecoderNano
(MyMessage.getDefaultInstance()));
// Encoder
pipeline.addLast("frameEncoder", new LengthFieldPrepender
(4));
pipeline.addLast("protobufEncoder", new ProtobufEncoderNano
());
然后您可以使用MyMessage
而不是ByteBuf
作为消息:
void channelRead(ChannelHandlerContext
ctx, Object msg) {
MyMessage req = (MyMessage) msg;
MyMessage res = MyMessage.newBuilder().setText(
"Did you say '" + req.getText() + "'?").build();
ch.write(res);
}
ChannelHandler.Sharable
Constructor and Description |
---|
ProtobufDecoderNano(java.lang.Class<? extends MessageNano> clazz)
创建一个新的实例。
|
Modifier and Type | Method and Description |
---|---|
protected void |
decode(ChannelHandlerContext ctx, ByteBuf msg, java.util.List<java.lang.Object> out)
从一条消息解码到另一条消息。
|
acceptInboundMessage, channelRead
channelActive, channelInactive, channelReadComplete, channelRegistered, channelUnregistered, channelWritabilityChanged, exceptionCaught, userEventTriggered
ensureNotSharable, handlerAdded, handlerRemoved, isSharable
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
handlerAdded, handlerRemoved
public ProtobufDecoderNano(java.lang.Class<? extends MessageNano> clazz)
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, java.util.List<java.lang.Object> out) throws java.lang.Exception
MessageToMessageDecoder
decode
在课堂上
MessageToMessageDecoder<ByteBuf>
ctx
- MessageToMessageDecoder
所属的ChannelHandlerContext
msg
- 解码到另一个的消息
out
- 应该添加解码消息的
List
java.lang.Exception
- 发生错误时抛出
Copyright © 2008–2018 The Netty Project. All rights reserved.