Netty权威指南之分隔符和定长解码器

来源:互联网 发布:键盘键位修改软件 编辑:程序博客网 时间:2024/05/16 17:36

本章需要学习的内容如下:

1、DelimiterBasedFrameDecode服务端开发

2、DelimiterBasedFreamDecode客户端开发

3、运行DelimiterBasedFreamDecode服务端和客户端

4、FixedLengthFrameDecoder服务端开发

5、通过telnet 命令调试FixedLengthFrameDecode 服务端



本章相关知识点补充:

TCP以流方式进行数据传输,上层的应用协议为了对消息进行区分,往往采用如下四种方式:

1、消息长度固定,累计读取到的长度总和为定长LEN 的报文后,就认为读取到了一个完整的消息;将计数器重置,重新读取下一个数据包。

2、将回车换行符作为消息结束符,例如:FTP协议,这种方式在文本协议中应用比较广泛。

3、将特殊的分割符作为消息结束标志,回车换行符就是一种消息结束分隔符。

4、通过在消息中定义长度字段来标示消息的总长度。


Netty 对上面四种应用做了统一抽象,提供四种解码器解决对应问题,使用起来很方便。有了这些解码器,用户不需要自己对读取的报文进行人工解码,也不需要考虑TCP粘包和拆包问题。


在上一讲中,我们曾经提到过使用LineBasedFraemDecoder解决TCP粘包的问题,本章节我们学习另外两种实用的解码器----------DelimiterBasedFreamDecoder和FixedLengthFrameDeceder。前者可以自动完成以分隔符做结束标志的消息解码,后者可以自动完成对定长消息的解码,它们都是解决TCP粘包和拆包的读半包问题。


第一节:DelimiterBasedFrameDecoder 服务端开发

通过对DelimiterBasedFrameDecoder的使用,我们可以自动完成以分隔符作为码流结束标示的消息解码。

(1)、创建Server 服务端Netty创建全部都是实现自AbstractBootstrap。客户端的是Bootstrap,服务端的则是ServerBootstrap。

HelloServer.java

package com.nio.server;import com.nio.handler.HelloServerInitializer;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioServerSocketChannel;/** * Created by vixuan-008 on 2015/6/22. */public class HelloServer {    /**     * 服务端监听的端口地址     */    private static final int portNumber = 7878;    public static void main(String[] args)throws InterruptedException{        EventLoopGroup bossGroup = new NioEventLoopGroup();        EventLoopGroup workerGroup = new NioEventLoopGroup();        try {            ServerBootstrap b = new ServerBootstrap();            b.group(bossGroup, workerGroup);            b.channel(NioServerSocketChannel.class);            b.childHandler(new HelloServerInitializer());            // 服务器绑定端口监听            ChannelFuture f = b.bind(portNumber).sync();            // 监听服务器关闭监听            f.channel().closeFuture().sync();            // 可以简写为            /* b.bind(portNumber).sync().channel().closeFuture().sync(); */        } finally {            bossGroup.shutdownGracefully();            workerGroup.shutdownGracefully();        }    }}

EventLoopGroup 是在4.x版本中提出来的一个新概念。用于channel的管理。服务端需要两个。和3.x版本一样,一个是boss线程一个是worker线程。

b.childHandler(new HelloServerInitializer());    //用于添加相关的Handler

服务端简单的代码,真的没有办法在精简了感觉。就是一个绑定端口操作。


(2)、创建和实现HelloServerInitializer在HelloServer中的HelloServerInitializer在这里实现

HelloServerInitializer.java

package com.nio.handler;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.socket.SocketChannel;import io.netty.handler.codec.DelimiterBasedFrameDecoder;import io.netty.handler.codec.Delimiters;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;/** * Created by vixuan-008 on 2015/6/22. */public class HelloServerInitializer extends ChannelInitializer<SocketChannel> {    @Override    protected void initChannel(SocketChannel socketChannel) throws Exception {        ChannelPipeline pipeline = socketChannel.pipeline();        // 以("\n")为结尾分割的 解码器        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192,                Delimiters.lineDelimiter()));        // 字符串解码 和 编码        pipeline.addLast("decoder", new StringDecoder());        pipeline.addLast("encoder", new StringEncoder());        // 自己的逻辑Handler        pipeline.addLast("handler", new HelloServerHandler());    }}

 首先我们需要明确我们到底是要做什么的。很简单。HelloWorld!。我们希望实现一个能够像服务端发送文字的功能。服务端假如可以最好还能返回点消息给客户端,然客户端去显示。

  需求简单。那我们下面就准备开始实现。

  DelimiterBasedFrameDecoder Netty在官方网站上提供的示例显示 有这么一个解码器可以简单的消息分割。

  其次 在decoder里面我们找到了String解码编码器。着都是官网提供给我们的。 

   上面的三个解码和编码都是系统。

  另外我们自己的Handler怎么办呢。在最后我们添加一个自己的Handler用于写自己的处理逻辑。


(3)、增加自己的逻辑HelloServerHandler

  自己的Handler我们这里先去继承extends官网推荐的SimpleChannelInboundHandler<C> 。在这里C,由于我们需求里面发送的是字符串。这里的C改写为String。

package com.nio.handler;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import java.net.InetAddress;/** * Created by vixuan-008 on 2015/6/22. */public class HelloServerHandler extends SimpleChannelInboundHandler<String> {    @Override    protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {    }    /*     *     * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)     *     * channelActive 和 channelInActive 在后面的内容中讲述,这里先不做详细的描述     */    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        System.out.println("RamoteAddress : " + ctx.channel().remoteAddress()                + " active !");        ctx.writeAndFlush("Welcome to "                + InetAddress.getLocalHost().getHostName() + " service!\n");        super.channelActive(ctx);    }    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        // 收到消息直接打印输出        System.out.println(ctx.channel().remoteAddress() + " Say : " + msg);        // 返回客户端消息 - 我已经接收到了你的消息        ctx.writeAndFlush("Received your message !\n");    }}

在channelHandlerContent自带一个writeAndFlush方法。方法的作用是写入Buffer并刷入。

  注意:在3.x版本中此处有很大区别。在3.x版本中write()方法是自动flush的。在4.x版本的前面几个版本也是一样的。但是在4.0.9之后修改为WriteAndFlush。普通的write方法将不会发送消息。需要手动在write之后flush()一次

  这里channeActive的意思是当连接活跃(建立)的时候触发.输出消息源的远程地址。并返回欢迎消息。

  channelRead0 在这里的作用是类似于3.x版本的messageReceived()。可以当做是每一次收到消息是触发。

  我们在这里的代码是返回客户端一个字符串"Received your message !".

  注意:字符串最后面的"\n"是必须的。因为我们在前面的解码器DelimiterBasedFrameDecoder是一个根据字符串结尾为“\n”来结尾的。假如没有这个字符的话。解码会出现问题。


第二章节:DelimiterBasedFreamDecode客户端开发

类似于服务端的代码。我们不做特别详细的解释。

  直接上示例代码:

package com.nio.client;import com.nio.handler.HelloClientInitializer;import io.netty.bootstrap.Bootstrap;import io.netty.channel.Channel;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioSocketChannel;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * Created by vixuan-008 on 2015/6/22. */public class HelloClient {    public static String host = "127.0.0.1";    public static int port = 7878;    /**     * @param args     * @throws InterruptedException     * @throws IOException     */    public static void main(String[] args)throws  InterruptedException,IOException{        EventLoopGroup group = new NioEventLoopGroup();        try {            Bootstrap b = new Bootstrap();            b.group(group).channel(NioSocketChannel.class)                    .handler(new HelloClientInitializer());            // 连接服务端            Channel ch = b.connect(host, port).sync().channel();            // 控制台输入            BufferedReader in = new BufferedReader(new InputStreamReader(                    System.in));            for (;;) {                String line = in.readLine();                if (line == null) {                    continue;                }                /*                 * 向服务端发送在控制台输入的文本 并用"\r\n"结尾 之所以用\r\n结尾 是因为我们在handler中添加了                 * DelimiterBasedFrameDecoder 帧解码。                 * 这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识别和解码                 */                ch.writeAndFlush(line + "\r\n");            }        } finally {            // The connection is closed automatically on shutdown.            group.shutdownGracefully();        }    }}
下面的是HelloClientInitializer代码貌似是和服务端的完全一样。我没注意看。其实编码和解码是相对的。多以服务端和客户端都是解码和编码。才能通信。
HelloClientInitializer.java
package com.nio.handler;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.socket.SocketChannel;import io.netty.handler.codec.DelimiterBasedFrameDecoder;import io.netty.handler.codec.Delimiters;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;/** * Created by vixuan-008 on 2015/6/22. */public class HelloClientInitializer extends ChannelInitializer<SocketChannel> {    @Override    protected void initChannel(SocketChannel ch) throws Exception {        ChannelPipeline pipeline = ch.pipeline();        /*         * 这个地方的 必须和服务端对应上。否则无法正常解码和编码         *         * 解码和编码 我将会在下一张为大家详细的讲解。再次暂时不做详细的描述         */        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192,                Delimiters.lineDelimiter()));        pipeline.addLast("decoder", new StringDecoder());        pipeline.addLast("encoder", new StringEncoder());        // 客户端的逻辑        pipeline.addLast("handler", new HelloClientHandler());    }}

HelloClientHandler.java
package com.nio.handler;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;/** * Created by vixuan-008 on 2015/6/22. */public class HelloClientHandler extends SimpleChannelInboundHandler<String> {    @Override    protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {    }    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        System.out.println("Server say : " + msg);    }    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        System.out.println("Client active ");        super.channelActive(ctx);    }    @Override    public void channelInactive(ChannelHandlerContext ctx) throws Exception {        System.out.println("Client close ");        super.channelInactive(ctx);    }}

第三节:运行DelimiterBasedFreamDecode服务端和客户端

下面上几张成果图:

  客户端在连接建立是输出了Client active 信息,并收到服务端返回的Welcome消息。

  输入Hello World ! 回车发送消息。服务端响应返回消息已接受。



  


第四节:FixedLengthFrameDecoder服务端开发

FixedLengthFrameDecoder是固定长度的解码器,它能够按照指定的长度对消息进行自动解码,开发者不需要了解TCP粘包和拆包,非常实用。

EchoServer.java

package com.nio.server;import com.nio.handler.EchoHandler;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import io.netty.handler.codec.FixedLengthFrameDecoder;import io.netty.handler.codec.string.StringDecoder;import java.io.IOException;/** * Created by vixuan-008 on 2015/6/22. */public class EchoServer {    /**     * 服务端监听的端口地址     */    private static final int portNumber = 7880;    public static void main(String[] args)throws InterruptedException,IOException{        EventLoopGroup bossGroup = new NioEventLoopGroup();        EventLoopGroup workerGroup = new NioEventLoopGroup();        try {            ServerBootstrap b = new ServerBootstrap();            b.group(bossGroup, workerGroup);            b.channel(NioServerSocketChannel.class);            b.option(ChannelOption.SO_BACKLOG, 100);            b.childHandler(new ChannelInitializer<SocketChannel>() {                @Override                protected void initChannel(SocketChannel socketChannel) throws Exception {                    socketChannel.pipeline().addLast(new FixedLengthFrameDecoder(20));                    socketChannel.pipeline().addLast(new StringDecoder());                    socketChannel.pipeline().addLast(new EchoHandler());                }            });                      // 服务器绑定端口监听            ChannelFuture f = b.bind(portNumber).sync();            // 监听服务器关闭监听            f.channel().closeFuture().sync();            // 可以简写为            /* b.bind(portNumber).sync().channel().closeFuture().sync(); */        } finally {            bossGroup.shutdownGracefully();            workerGroup.shutdownGracefully();        }    }}

EchoHandler.java 的功能比较简单,直接将读取到的消息打印出来。

package com.nio.handler;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;/** * Created by vixuan-008 on 2015/6/22. */public class EchoHandler extends ChannelHandlerAdapter {    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {        ctx.close();    }    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        String body=(String)msg;        System.out.println("Receiver client:{"+body+"}");    }}

第五节:通过telnet 命令调试FixedLengthFrameDecode 服务端


服务端信息:


  






0 0
原创粉丝点击