在上一篇文章中有分享了一个比较好的博客地址:http://asialee.iteye.com/blog/1769508
里面有详细介绍一些原理方面的知识,还有简单的使用。
而编码和解码,我想实现通过字符串,以“XXEE”作为分割符。
public final class Delimiters { public static ByteBuf[] XXEEDelimiter() { return new ByteBuf[] { Unpooled.wrappedBuffer("XXEE".getBytes()) }; } }
显而易见,返回XXEE的Delimiters。
public class PipelineFactory extends ChannelInitializer<SocketChannel> { private static final StringDecoder DECODER = new StringDecoder(); private static final StringEncoder ENCODER = new StringEncoder(BufType.BYTE); private static final MessageCodec MSGCODEC = new MessageCodec(); private static final TcpServerHandler TCPSERVERHANDLE = new TcpServerHandler(); @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //不过滤分隔符 pipeline.addLast("frame", new DelimiterBasedFrameDecoder(8192, false, Delimiters.XXEEDelimiter())); pipeline.addLast("decoder", DECODER); pipeline.addLast("encoder", ENCODER); //用MessageCodec过滤和组装分隔符 pipeline.addLast("msgcodec", MSGCODEC); pipeline.addLast("handler", TCPSERVERHANDLE); } }
MessageCodec实现如下:
@Sharable public class MessageCodec extends MessageToMessageCodec<String, String> { @Override public String encode(ChannelHandlerContext ctx, String msg) throws Exception { return msg + "XXEE"; } @Override public String decode(ChannelHandlerContext ctx, String msg) throws Exception { return msg.substring(0, msg.lastIndexOf("XXEE")); } }
实现非常简单,通过分隔符过滤后,再用StringDecode转换成String,然后通过MessageCodec过滤分隔符。发消息时,反过来的流程。