Skip to content

Latest commit

 

History

History
42 lines (29 loc) · 1.41 KB

netty-message-to-message-codec.md

File metadata and controls

42 lines (29 loc) · 1.41 KB

MessageToMessageCodec

Decoder&Encoder

  • MessageToMessageDecoder
  • MessageToMessageEncoder

通过下面二个类的相关的功能,分析MessageToMessageCodec的用法

  • StringDecoder
  • StringEncoder

usage

StringDecoder,StringEncoder 可以再 netty 中进行基于String类型的数据通信

  • StringDecoderByteBuf转化为String,把接受到的 byte 字节,转化为 String
  • StringEncoderString转化为ByteBuf,把String转化为byte字节,进行网络的传输

demo

Decodes a received ByteBuf into a String. Please note that this decoder must be used with a proper ByteToMessageDecoder such as DelimiterBasedFrameDecoder or LineBasedFrameDecoder if you are using a stream-based transport such as TCP/IP. A typical setup for a text-based line protocol in a TCP/IP socket would be:

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));

// and then you can use a String instead of a ByteBuf as a message:
void channelRead(ChannelHandlerContext ctx, String msg) {
     ch.write("Did you say '" + msg + "'?\n");
}