[toc]


Netty中定长×××的使用

有了前面的基础,定长×××的使用相对就比较简单了,所以这里只使用服务端的代码,测试时,用telnet作为客户客户端,数据只作单向的发送,即从客户端到服务端。

服务端

EchoServer.java

package cn.xpleaf.netty02;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
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.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

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, 1024)
                .childHandler(new ChannelInitializer() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 添加定长分隔符×××到pipeline中,长度设置为20
                        ch.pipeline().addLast(new FixedLengthFrameDecoder(20));
                        // 添加StringDecoder×××,将ByteBuf解码成字符串对象
                        ch.pipeline().addLast(new StringDecoder());
                        // 添加业务处理handler
                        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(port);
            } catch (NumberFormatException e) {
                // TODO: handle exception
            }
        }
        new EchoServer().bind(port);
    }
}

EchoServerHandler.java

package cn.xpleaf.netty02;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    private int counter = 0;

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

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

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

测试

启动服务端,在telnet客户端中输入相应字符串:

yeyonghao@yeyonghaodeMacBook-Pro:~$ telnet localhost 8080
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Ye Yonghao welcome to Beijing

此时查看服务端的输出:

Receive client : [Ye Yonghao welcome t]

可以看到中括号时字符数刚好是20个,因为在pipeline中设置定长×××时,设置的长度就是20。

可以尝试再发送消息:

yeyonghao@yeyonghaodeMacBook-Pro:~$ telnet localhost 8080
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Ye Yonghao welcome to Beijing
I love you so much!

再查看服务端的输出:

Receive client : [Ye Yonghao welcome t]
Receive client : [o Beijing
I love yo]

可以看到服务端把上一次的消息作为这次消息的开始,包括换行符,这说明定长×××确实是有效果了。