@ChannelHandler.Sharable public class StringDecoder extends MessageToMessageDecoder<ByteBuf>
ByteBuf解码为String 。
请注意,如果您正在使用基于流的传输(如TCP / IP),则必须将此解码器与ByteToMessageDecoder一起使用,例如DelimiterBasedFrameDecoder或LineBasedFrameDecoder 。
TCP / IP套接字中基于文本的行协议的典型设置为:
ChannelPipeline pipeline = ...;
// Decoders
pipeline.addLast("frameDecoder", new LineBasedFrameDecoder(80));
pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
// Encoder
pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
然后您可以使用String而不是ByteBuf作为消息:
void channelRead(ChannelHandlerContext ctx, String msg) {
ch.write("Did you say '" + msg + "'?\n");
}
ChannelHandler.Sharable| Constructor and Description |
|---|
StringDecoder()
用当前系统字符集创建一个新实例。
|
StringDecoder(java.nio.charset.Charset charset)
用指定的字符集创建一个新的实例。
|
| Modifier and Type | Method and Description |
|---|---|
protected void |
decode(ChannelHandlerContext ctx, ByteBuf msg, java.util.List<java.lang.Object> out)
从一条消息解码到另一条消息。
|
acceptInboundMessage, channelReadchannelActive, channelInactive, channelReadComplete, channelRegistered, channelUnregistered, channelWritabilityChanged, exceptionCaught, userEventTriggeredensureNotSharable, handlerAdded, handlerRemoved, isSharableclone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waithandlerAdded, handlerRemovedpublic StringDecoder()
public StringDecoder(java.nio.charset.Charset charset)
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.