Netty开发入门(参考netty权威指南第二版)

netty开发包版本4.1.6
netty权威指南第二版
netty客户端代码:
启动类:NettyClient

package com.netty.client.test;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
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.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class NettyClient {
    public void connect(int port, String host) throws InterruptedException {
        //配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();//创建客户端辅助启动类
            b.group(group).channel(NioSocketChannel.class)//设置channel
                    .option(ChannelOption.TCP_NODELAY, true)
                    //.remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {//添加handler
                        //当NioSocketChannel创建成功后,进行初始化
                        @Override
                        protected void initChannel(SocketChannel ch)
                                throws Exception {
                            // TODO Auto-generated method stub
                            //以回车换行作为分隔符的解码器
                            /*ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            */
                            //以"$_"作为分隔符
                            ByteBuf delimiter=Unpooled.copiedBuffer("$_".getBytes());
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                            ch.pipeline().addLast(new StringDecoder());//将接收到的对象转换成字符串
                            ch.pipeline().addLast(new NettyTimeClientHandler());//设置ChannelHandler处理网络I/O事件
                        }
                    });
            //发起异步连接操作
            ChannelFuture f=b.connect(host, port).sync();
            f.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture arg0) throws Exception {
                    // TODO Auto-generated method stub
                    if(arg0.isSuccess()){
                        System.out.println("client successed");
                    }else{
                        System.out.println("server attemp failed");
                        arg0.cause().printStackTrace();
                    }
                }
            });
            //等待客户端链路关闭
            f.channel().closeFuture().sync();
        }finally{
            System.out.println(NettyClient.class.getName()+" close");
            group.shutdownGracefully();//优雅退出,释放NIO线程组
        }

    }

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

        new NettyClient().connect(port, "192.168.1.159");

    }


}

I/O处理类NettyTimeClientHandler:

package com.netty.client.test;

import java.util.logging.Logger;

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

public class NettyTimeClientHandler extends ChannelInboundHandlerAdapter{

    private static final Logger logger=Logger.getLogger(NettyTimeClientHandler.class.getName());
    //private final ByteBuf firstMessage;
    private byte[] req;
    private int counter;
    static final String ECHO_REQ="Hi, Lilinfeng. Welcome to Netty.$_";
    public NettyTimeClientHandler(){
        req=("QUERY TIME ORDER"+System.getProperty("line.separator")).getBytes();
        //firstMessage=Unpooled.buffer(req.length);
        //firstMessage.writeBytes(req);
    }
    /*当客户端和服务器端TCP链路建立成功后,Netty的NIO线程会调用此方法
     *在本例中是发送查询时间的指令给服务器 
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        //super.channelActive(ctx);
        System.out.println("client channelActive");
        /*以回车换行作为分隔符
        ByteBuf firstMessage=null;
        for(int i=0;i<100;i++){
            firstMessage=Unpooled.buffer(req.length);
            firstMessage.writeBytes(req);
            ctx.writeAndFlush(firstMessage);//将消息发送给服务端
        }*/

        for(int i=0;i<10;i++){
            ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
        }

    }

    /**
     * 当服务端返回应答消息时,此方法被调用
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        // TODO Auto-generated method stub
        //super.channelRead(ctx, msg);
        System.out.println("client channelRead");
        /*ByteBuf buf=(ByteBuf) msg;
        byte[] req=new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body=new String(req, "UTF-8");*/

        /*String body=(String) msg;
        System.out.println("Now is : "+body+"; the counter is : "+ ++counter);*/

        System.out.println("This is "+ ++counter+" times receive server ["+msg+"]");
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        //super.channelReadComplete(ctx);
        ctx.flush();
    }
    /**
     * 当发送异常时,打印异常日志,释放客户端资源
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        // TODO Auto-generated method stub
        //super.exceptionCaught(ctx, cause);
        System.out.println("client exceptionCaught");
        logger.warning("Unexpected exception from downstream : "+cause.getMessage());
        //释放资源
        ctx.close();
    }

}

服务器端:
启动类NettyTimeService:

package com.zyc.netty;

import java.net.InetSocketAddress;

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.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;

public class NettyTimeService {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                //采用默认值
            }
        }
        new NettyTimeService().bind(port);
    }

    private void bind(int port) {
        // TODO Auto-generated method stub
        //配置服务端的NIO线程组,创建两个线程,一个用于服务端接受客户端的连接,另一个用于进行SocketChannel的网络读写
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();//启动NIO服务端胡辅助启动类
            b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)//将channel配置为NioServerSocketChannel
                    .option(ChannelOption.SO_BACKLOG, 1024)//配置tcp的参数
                    //.handler(new LoggingHandler(LogLevel.INFO))
                    //.localAddress(new InetSocketAddress(port))
                    .childHandler(new ChildChannelHandler());//绑定I/O事件胡处理类,主要处理网络I/O事件,例如记录日志,对消息进行编解码等
            //绑定端口,同步等待成功
            ChannelFuture f=b.bind(port).sync();//绑定监听端口,调用同步阻塞方法sync等待绑定操作完成,完成之后返回一个ChannelFuture
            System.out.println(NettyTimeService.class.getName()+" start and listen on"+f.channel().localAddress());
            //等待服务器监听端口关闭
            f.channel().closeFuture().sync();//等待服务端链路关闭之后才退出main函数
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }finally{
            //优雅推出,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }
    private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            // TODO Auto-generated method stub
            //以回车换行作为特殊字符解码器
            /*ch.pipeline().addLast(new LineBasedFrameDecoder(1024));依次遍历ByteBuf中的可读字节,判断看是否有"\n"或者"\r\n"//
            */

            //以"$_"作为分隔符的解码器
            /*ByteBuf delimiter=Unpooled.copiedBuffer("$_".getBytes());//分割符缓冲对象
            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));//1024表示单条消息胡最大长度,当大刀该长度后仍然没有查找到分割符就抛出TooLongFrame Exception异常
            */

            //固定长度解码器
            ch.pipeline().addLast(new FixedLengthFrameDecoder(20));
            ch.pipeline().addLast(new StringDecoder());//将接收到的对象转换成字符串
            ch.pipeline().addLast(new NettyTimeServerHandler());
        }

    }
}

I/0处理类NettyTimeServerHandler:

package com.zyc.netty;

import java.util.Date;
import java.util.logging.Logger;

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

/**
 * @author root 主要对网路事件进行读写操作,通常只需关注channelread肯exceptioncaught方法
 */
public class NettyTimeServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = Logger
            .getLogger(NettyTimeServerHandler.class.getName());
    private int counter;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        // TODO Auto-generated method stub
        // super.channelRead(ctx, msg);
        System.out.println("service channelRead");

/*没有增加拆包粘包处理    
        ByteBuf buf = (ByteBuf) msg;// 将msg转换成netty的ByteBuf对象,相当于ByteBuffer对象,不过它提供了更加强大和灵活的功能
        byte[] req = new byte[buf.readableBytes()];// 获取缓冲匀可读胡字节数,根据可读胡字节数创建byte数组
        buf.readBytes(req);// 将缓冲区中的字节数组复制到新建胡byte数组中
        String body = new String(req, "UTF-8").substring(0, req.length
                - System.getProperty("line.separator").length());// 删除回车换行
*/
        /*增加了以回车换行为分割符号的处理
         String body = (String) msg;
        System.out.println("The time server receive order : " + body
                + "; the counter is : " + ++counter);
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(
                System.currentTimeMillis()).toString() : "BAD ORDER";
        currentTime += System.getProperty("line.separator");// 增加回车换行分隔标志
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.write(resp);// 异步发送应答消息给客户端
*/
    //以"$_"为分割符号的处理
/*      String body=(String) msg;
        System.out.println("This is "+ ++counter+" times receive client : ["+body+"]");
        body +="$_";
        ByteBuf echo=Unpooled.copiedBuffer(body.getBytes());
        ctx.writeAndFlush(echo);*/

        System.out.println("Receive client : ["+msg+" ]");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        // super.channelReadComplete(ctx);
        System.out.println("service channelReadComplete");
        ctx.flush();// 将消息发送队列中胡消息写入到SocketChannel中发送给对方
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        // TODO Auto-generated method stub
        // super.exceptionCaught(ctx, cause);
        System.out.println("service exceptionCaught");
        logger.warning("Unexpected exception form downstream : "
                + cause.getMessage());
        ctx.close();// 关闭ctx,释放和ctx相关联的句柄等资源
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值