@ChannelHandler.Sharable public class ProtobufDecoder extends MessageToMessageDecoder<ByteBuf>
ByteBuf
解码为Google Protocol Buffers Message
和MessageLite
。
请注意,如果您使用基于流的传输(如TCP / IP),则必须将此解码器与ByteToMessageDecoder
(例如ProtobufVarint32FrameDecoder
或LengthFieldBasedFrameDecoder
)一起使用。
TCP / IP的典型设置是:
ChannelPipeline
pipeline = ...;
// Decoders
pipeline.addLast("frameDecoder",
new LengthFieldBasedFrameDecoder
(1048576, 0, 4, 0, 4));
pipeline.addLast("protobufDecoder",
new ProtobufDecoder
(MyMessage.getDefaultInstance()));
// Encoder
pipeline.addLast("frameEncoder", new LengthFieldPrepender
(4));
pipeline.addLast("protobufEncoder", new ProtobufEncoder
());
然后您可以使用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 |
---|
ProtobufDecoder(MessageLite prototype)
创建一个新的实例。
|
ProtobufDecoder(MessageLite prototype, ExtensionRegistry extensionRegistry) |
ProtobufDecoder(MessageLite prototype, ExtensionRegistryLite extensionRegistry) |
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 ProtobufDecoder(MessageLite prototype)
public ProtobufDecoder(MessageLite prototype, ExtensionRegistry extensionRegistry)
public ProtobufDecoder(MessageLite prototype, ExtensionRegistryLite extensionRegistry)
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.