Netty学习之路——从入门到入坟

Java网络编程学习笔记(未完待续)

写给自己的,也写给大家一起学习,有错误的地方欢迎交流。Over
参考:1.马士兵老师的公开课

IO(Input/Output)模型

BIO -> NIO -> AIO

  • BIO:Blocking IO,阻塞IO
  • NIO:Non-Blocking IO,非阻塞IO
    • Single thread,单线程模型
    • Reactor模式
  • AIO:AsyncAsynchronous IO,异步IO(不再需要轮询)
    • 设计模式:观察者(Observer)模式

Netty

Netty实际上是对NIO进行了封装,提供了更好用的API,写法有些类似于AIO。
Netty提供了io.netty.channel.nio.NioEventLoopGroup;类,类似于AIO中的ExcutorService+AsynchronousChannelGroup的作用。另外它提供了io.netty.buffer.ByteBuf;类用来代替java.nio.ByteBuffer;显然Netty提供的ByteBuf更加好用

  • 方便理解直接上Netty的Server端示例代码。这里throws了Exception用来精简代码,实际开发中不推荐使用。
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;


public class HelloNetty{
    public static void main(String[] args) {
        new NettyServer(8888).serverStart();
    }
}

class NettyServer {

    int port = 8888;

    public NettyServer(int port){
        this.port = port;
    }

    public void serverStart(){
        /**
        *bossGroup负责建立连接,类似selector
        *workerGroup负责进行真正的进行读写等操作,连接建立后boosGroup会把工作交给worker
        *这两个可以理解成两个线程池,可以加int型参数
        */
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        /**
        *对server启动进行一些配置,类似于启动器
        */
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        /**
        *group方法的第一个参数负责连接,第二个参数负责连接之后的IO处理
        *channel指定了连接的通道类型
        *childHandler意思是当有客户端连接上之后指定一个监听器去处理,这个监听器处理的过程是在这个通道上加一个处理器(又是一个监听器)去处理。在这里我认为这是两个钩子函数,当有客户端连接时调用,当有IO操作时调用
        **/
        serverBootstrap
                .group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new Handler());
                    }
                });
        try{
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }
}

/**
*自定义的处理器,通过addLast方法加入到处理逻辑中,这里的逻辑是当通道可以读的时候就进行读取,并把结果写回给客户端
*/
class Handler extends ChannelInboundHandlerAdapter{
    /**   
    *当通道可读时进行读取,并写回给客户端,然后关闭通道
    */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server : channel read");
        ByteBuf byteBuf = (ByteBuf)msg;
        System.out.println(byteBuf.toString(CharsetUtil.UTF_8));
        ctx.writeAndFlush(msg);
        ctx.close();
    }
    /**
    *处理异常的函数,一般来说需要关闭通道
    */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
  • Netty的Client端
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

public class Client {
    public static void main(String[] args) {
        new Client().clientStart();
    }

    public void clientStart(){
        /**
        *Client端只需要workers
        */
        EventLoopGroup workers = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        /**
        *这里的handler中的参数是在通道初始化时将自己的Handler调用
        */
        bootstrap
                .group(workers)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        System.out.println("chanenel initialized!");
                        socketChannel.pipeline().addLast(new ClientHandler());
                    }
                });
        try {
            System.out.println("Start to connect!");
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",8888);

            channelFuture.channel().closeFuture().sync();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            workers.shutdownGracefully();
        }
    }
}

/**
*自己的Handler逻辑
*这里的思路是当通道激活时向服务器写入"Hellow Netty"
*当通道可读时读取通道上的内容并打印
*/
class ClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Channel is activated!");
        final ChannelFuture channelFuture = ctx.writeAndFlush(Unpooled.copiedBuffer("HelloNetty".getBytes()));
        channelFuture.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                System.out.println("msg send!");
            }
        });

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf byteBuf = (ByteBuf)msg;
            System.out.println(byteBuf.toString(CharsetUtil.UTF_8));
        }
        finally {
            ReferenceCountUtil.release(msg);
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值