netty权威指南~第5章——分隔符和定长解码器的应用

TCP 以 流 的 方 式 进 行 数 据 传 输 , 上 层 的 应 用 协 议 为 了 对 消 息 进 行 区 分 , 往 往 采 用 如 下4 种 方 式 。
( 1 ) 消 息 长 度 固 定 , 累 计 读 取 到 长 度 总 和 为 定 长 L EN 的 报 文 后 , 就 认 为 读 取 到 了 一个 完 整 的 消 息 ; 将 计 数 器 置 位 , 重 新 开 始 读 取 下 一 个 数 据 报 :
( 2 ) 将 回 车 换 行 符 作 为 消 息 结 束 符 , 例 如 FTP 协 议 , 这 种 方 式 在 文 本 协 议 中 应 用 比 较
( 3 ) 将 特 殊 的 分 隔 符 作 为 消 息 的 结 束 标 志 , 回 车 换 行 符 就 是 一 种 特 殊 的 结 束 分 隔 符 ;
( 4 ) 通 过 在 消 息 头 中 定 义 长 度 字 段 来 标 识 消 息 的 总 长 度 。
Netty 对 上 面 4 种 应 用 做 了 统 一 的 抽 象 , 提 供 了 4 种 解 码 器 来 解 决 对 应 的 问 题 ,使用起 来 非 常 方 便 。 有 了 这 些 解 码 器 , 用 户 不 需 要 自 己 对 读 取 的 报 文 进 行 人 工 解 码 , 也 不 需 要考 虑 TCP 的 粘 包 和 拆 包 。

5.1DelimiterBasedFrameDecoder 应用开发

5.1.1 DelimiterBasedFrameDecoder 服务端开发

  • EchoServer.java
public class EchoServer {
    public void bind(int port) throws Exception {
        // 配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {

                            ByteBuf delimiter = Unpooled
                                    .copiedBuffer("$_".getBytes());
                            ch.pipeline()
                                    .addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new EchoServerHandler());

                        }
                    });

            // 绑定端口,同步等待成功
            ChannelFuture f = b.bind(port).sync();

            // 等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                // 采用默认值
            }
        }
        new EchoServer().bind(port);
    }
}

我 们 重 点 看 17~20 行 , 首 先 创 建 分 隔 符 缓 冲 对 象 ByteBuf , 本 例 程 中 使 用 “ $_” 作 为分 隔 符 。 第 20 行 , 创 建 DeIimiterBasedFrameDecoder 对 象 , 将 其 加 入 到 ChannelPipeline中 。 DeIimiterBasedFrameDecoder 有 多 个 构 造 方 法 , 这 里 我 们 传 递 两 个 参 数 : 第 一 个 1024表 示 单 条 消 息 的 最 大 长 度 , 当 达 到 该 长 度 后 仍 然 没 有 查 找 到 分 隔 符 , 就 抛 出 TooLongFrameException 异 常 , 防 止 山 于 异 常 码 流 缺 失 分 隔 符 导 致 的 内 存 溢 出 , 这 是 Netty 解 码 器 的 可 靠性 保 护 ; 第 二 个 参 数 就 是 分 隔 符 缓 冲 对 象 。

  • EchoServerHandler.java
public class EchoServerHandler extends ChannelHandlerAdapter {

    int counter = 0;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        String body = (String) msg;
        System.out.println("This is " + ++counter + " times receive client : ["
                + body + "]");
        body += "$_";
        ByteBuf echo = Unpooled.copiedBuffer(body.getBytes());
        ctx.writeAndFlush(echo);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();// 发生异常,关闭链路
    }
}

第 8~10 行 直 接 将 接 收 的 消 息 打 印 出 来 , 由 于 DelimiterBasedFrameDecoder 自 动 对 请求 消 息 进 行 了 解 码 , 后 续 的 ChannelHandler 接 收 到 的 msg 对 象 就 是 个 完 整 的 消 息 包 : 第 二个 ChannelHandler 是 StringDecoder , 它 将 ByteBuf 解 码 成 字 符 串 对 象 : 第 三 个EchoServerHandler 接 收 到 的 msg 消 息 就 是 解 码 后 的 字 符 串 对 象 。由 于 我 们 设 置 DelimiterBasedFrameDecoder 过 滤 掉 了 分 隔 符 , 所 以 , 返 回 给 客 户 端时 需 要 在 请 求 消 息 尾 部 拼 接 分 隔 符 “ $_ ” , 最 后 创 建 ByteBuf , 将 原 始 消 息 重 新 返 回 给客 户 端 。

5.1.1 DelimiterBasedFrameDecoder 客户端开发

  • EchoClient.java
public class EchoClient  {
    public void connect(int port, String host) throws Exception {
        // 配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ByteBuf delimiter = Unpooled.copiedBuffer("$_"
                                    .getBytes());
                            ch.pipeline().addLast(
                                    new DelimiterBasedFrameDecoder(1024,
                                            delimiter));
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new EchoClientHandler());
                        }
                    });

            // 发起异步连接操作
            ChannelFuture f = b.connect(host, port).sync();

            // 当代客户端链路关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出,释放NIO线程组
            group.shutdownGracefully();
        }
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                // 采用默认值
            }
        }
        new EchoClient().connect(port, "127.0.0.1");
    }
}

  • EchoClientHandler.java
public class EchoClientHandler extends ChannelHandlerAdapter {

    private int counter;

    static final String ECHO_REQ = "Hi, Lilinfeng. Welcome to Netty.$_";

    /**
     * Creates a client-side handler.
     */
    public EchoClientHandler() {
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // ByteBuf buf = UnpooledByteBufAllocator.DEFAULT.buffer(ECHO_REQ
        // .getBytes().length);
        // buf.writeBytes(ECHO_REQ.getBytes());
        for (int i = 0; i < 10; i++) {
            ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        System.out.println("This is " + ++counter + " times receive server : ["
                + msg + "]");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

第 18~20 行 在 TCP 链 路 建 立 成 功 之 后 循 环 发 送 请 求 消 息 给 服 务 端 , 第26-27行 打印 接 收 到 的 服 务 端 应 答 消 息 同 时 进 行 计 数 。

5.1.2 运行结果

在这里插入图片描述
在这里插入图片描述
本 例 程 运 行 1 0 次 的 原 因 是 模 拟 TCP 粘 包 / 拆 包 , 在 笔 者 的 机 器 上 , 连 续 发 送 1 0 条 Echo请 求 消 息 会 发 生 粘 包 , 如 果 没 有 DeIimiterBasedFrameDecoder 解 码 器 的 处 理 , 服 务 端 和 客户 端 程 序 都 将 运 行 失 败 。
下 面 我 们 将 服 务 端 的 DeIimiterBasedFrameDecoder 注 释 掉 , 最 终代 码 如 图 所 示 。
在这里插入图片描述

5.2 FixedLengthFrameDecoder 应用开发

  • EchoServer.java
/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.phei.netty.frame.fixedLen;

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 io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author lilinfeng
 * @date 2014年2月14日
 * @version 1.0
 */
public class EchoServer {
    public void bind(int port) throws Exception {
	// 配置服务端的NIO线程组
	EventLoopGroup bossGroup = new NioEventLoopGroup();
	EventLoopGroup workerGroup = new NioEventLoopGroup();
	try {
	    ServerBootstrap b = new ServerBootstrap();
	    b.group(bossGroup, workerGroup)
		    .channel(NioServerSocketChannel.class)
		    .option(ChannelOption.SO_BACKLOG, 100)
		    .handler(new LoggingHandler(LogLevel.INFO))
		    .childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch)
				throws Exception {
			    ch.pipeline().addLast(
				    new FixedLengthFrameDecoder(20));
			    ch.pipeline().addLast(new StringDecoder());
			    ch.pipeline().addLast(new EchoServerHandler());
			}
		    });

	    // 绑定端口,同步等待成功
	    ChannelFuture f = b.bind(port).sync();

	    // 等待服务端监听端口关闭
	    f.channel().closeFuture().sync();
	} finally {
	    // 优雅退出,释放线程池资源
	    bossGroup.shutdownGracefully();
	    workerGroup.shutdownGracefully();
	}
    }

    public static void main(String[] args) throws Exception {
	int port = 8080;
	if (args != null && args.length > 0) {
	    try {
		port = Integer.valueOf(args[0]);
	    } catch (NumberFormatException e) {
		// 采用默认值
	    }
	}
	new EchoServer().bind(port);
    }
}

  • EchoServerHandler.java
/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.phei.netty.frame.fixedLen;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author lilinfeng
 * @date 2014年2月14日
 * @version 1.0
 */
@Sharable
public class EchoServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
	    throws Exception {
	System.out.println("Receive client : [" + msg + "]");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
	cause.printStackTrace();
	ctx.close();// 发生异常,关闭链路
    }
}

利 用 FixedLengthFrameDecoder 解 码 器 , 无 论 . 次 接 收 到 多 少 数 据 报 , 它 都 会 按 照 构造 函 数 中 设 置 的 固 定 长 度 进 行 解 码 , 如 果 是 半 包 消 息 , FixedLengthFrameDecoder 会 缓 存半 包 消 息 并 等 待 下 个 包 到 达 后 进 行 拼 包 , 直 到 读 取 到 一 个 完 整 的 包 。
使用telnet命令进行的测试

5.3 总结

DeIimiterBasedFrameDecoder 用 于 对 使 用 分 隔 符 结 尾 的 消 息 进 行 自 动 解 码 ,FixedLengthFrameDecoder 用 于 对 固 定 长 度 的 消 息 进 行 自 动 解 码 。 有 了 上 述 两 种 解 码 器 ,再 结 合 其 他 的 解 码 器 , 如 字 符 串 解 码 器 等 , 可 以 轻 松 地 完 成 对 很 多 消 息 的 自 动 解 码 , 而 且不 再 需 要 考 虑 TCP 粘 包 / 拆 包 导 致 的 读 半 包 问 题 , 极 大 地 提 升 了 开 发 效 率 。应 用 Del imiterBasedFrameDecoder 和 FixedLengthFrameDecoder 进 行 开 发 非 常 简 单 ,在 绝 大 数 情 况 下 , 只 要 将 DelimiterBasedFrameDecoder 或 FixedLength FrameDecoder 添 加到 对 应 ChannelPipeline 的 起 始 位 即 可 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值