三、netty基本入门

来源:互联网 发布:搜狗小说书架数据恢复 编辑:程序博客网 时间:2024/05/18 00:52

作为netty的第一个应用程序,入门就好,明白几个接口的含义即可。

开发工具: IntelliJ IDEA 2016.2.2(64)
系统环境: win 10

服务端:

package nettyServer;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 L_kanglin on 2017/5/7. */public class nettyServer {    private static final int port=9030;    public static void main(String[] args) throws InterruptedException {        //第一个用于接收Client端连接的        //第二个线程组是用于实际的业务处理的        //创建了两个NioEventLoopGroup实例,NioEventLoopGroup        //是一个线程组,它包含了一组NIO线程,专门用于网络事件        //的处理        EventLoopGroup bossGroup = new NioEventLoopGroup();        EventLoopGroup workerGroup=new NioEventLoopGroup();        try{            ServerBootstrap b = new ServerBootstrap();            b.group(bossGroup,workerGroup);            b.channel(NioServerSocketChannel.class);            b.childHandler(new nettyServerInitializer());            //服务器绑定端口监听            ChannelFuture f= b.bind(port).sync();            //监听服务器关闭监听            f.channel().closeFuture().sync();        } finally{            bossGroup.shutdownGracefully();            workerGroup.shutdownGracefully();        }    }}
package nettyServer;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 L_kanglin on 2017/5/7. */public class nettyServerInitializer extends ChannelInitializer<SocketChannel> {    @Override    protected void initChannel(SocketChannel ch) throws Exception {        ChannelPipeline pipeline = ch.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 nettyServerHandler());    }}
package nettyServer;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import java.net.InetAddress;/** * Created by L_kanglin on 2017/5/7. */public class nettyServerHandler extends SimpleChannelInboundHandler<String> {    @Override    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {        System.out.println(ctx.channel().remoteAddress()+" Say:  "+msg);        //返回客户端消息--我已经收到了你的消息        //下面的write和flush方法是后面版本更新后,结合在一起的        //通过ChannelHandlerContext的write方法异步发送应答消息给客户端        //通过flush方法是将消息发送队列中的消息写入到SocketChannel中发送给对方        //从性能角度考虑,为了防止频繁的唤醒selector进行消息发送,netty的write方法并不直接将消息        //写入SocketChannel中,调用write方法只是把待发送的罅隙放到发送缓冲数组中,通过调用flush方法        //将发送缓冲区中的消息全部写到SocketChannel中        ctx.writeAndFlush("Received your message!\n");    }    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        System.out.println("RemoteAddress : "+ctx.channel().remoteAddress()+" active !");        ctx.writeAndFlush("Welcome to "+ InetAddress.getLocalHost().getHostName()+" service!\n");        super.channelActive(ctx);    }}

创建了两个NioEventLoopGroup实例。NioEventloopGroup是个线程组,它包含了一组NIO线程,专门用于网络事件的处理,实际上它们就是Reactor线程组。这里创建两个的原因是一个用于服务端接收客户端的连接,另一个用于进行SocketChannel的网络读写。
创建ServerBootstrap对象,它是netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度,调用了ServerBootstrap的group方法,将两个NIO线程组当做入参传递到ServerBootstrap中。
接着设置创建的Channel为NioServerSocketChannel,它的功能对应于JDK NIO类库中的ServerSocketChannel类,然后配置NioServerSocketChannel的TCP参数,此处将它的backlog设置为1024,最后绑定IO事件的处理类ChildChannelHandler,他的作用类似于Reactor模式中的handler类,主要用于处理网络的IO事件,例如记录日志、对消息进行编解码等。
服务端启动辅助类配置完成之后,调用它的bind方法绑定监听端口,随后,调用它的同步阻塞方法sync等待绑定操作完成。完成之后Netty会返回一个ChannelFuture,它的功能类似于JDK的Java.util.concurrent.Future,主要用于异步操作的通知回调。
f.cahnnel().closeFuture().sync()方法进行阻塞,等待服务器链路关闭之后main函数才退出。

调用NIO线程组的shutdpwnGracefully进行优雅退出,它会释放跟shutdownGracefully相关联的资源。
客户端:

package nettyServer;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import java.net.InetAddress;/** * Created by L_kanglin on 2017/5/7. */public class nettyServerHandler extends SimpleChannelInboundHandler<String> {    @Override    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {        System.out.println(ctx.channel().remoteAddress()+" Say:  "+msg);        //返回客户端消息--我已经收到了你的消息        //下面的write和flush方法是后面版本更新后,结合在一起的        //通过ChannelHandlerContext的write方法异步发送应答消息给客户端        //通过flush方法是将消息发送队列中的消息写入到SocketChannel中发送给对方        //从性能角度考虑,为了防止频繁的唤醒selector进行消息发送,netty的write方法并不直接将消息        //写入SocketChannel中,调用write方法只是把待发送的罅隙放到发送缓冲数组中,通过调用flush方法        //将发送缓冲区中的消息全部写到SocketChannel中        ctx.writeAndFlush("Received your message!\n");    }    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        System.out.println("RemoteAddress : "+ctx.channel().remoteAddress()+" active !");        ctx.writeAndFlush("Welcome to "+ InetAddress.getLocalHost().getHostName()+" service!\n");        super.channelActive(ctx);    }}
package nettyClient;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 L_kanglin on 2017/5/7. */public class nettyClientInitializer 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 nettyClientHandler());    }}
package nettyClient;import io.netty.channel.ChannelHandler;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;/** * Created by L_kanglin on 2017/5/7. */public class nettyClientHandler extends SimpleChannelInboundHandler<String>{    @Override    protected void channelRead0(ChannelHandlerContext ctx, String 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);    }}

客户端
重点关注三个方法:channelActive、channelRead和exceptionCaught。
当客户端和服务端TCP链路建立成功之后,Netty的NIO线程会调用channelActive方法,发送消息给服务端,调用ChannelHahndlerContext的writeAndFlush方法将请求消息发送给服务端。
当服务端返回应答消息时,channelRead方法被调用,从Netty的ByteBuf中读取并打印应答消息。
当发生异常时,打印异常日志,释放客户端资源。

运行结果如下:
Server

Client

参考书籍:netty权威指南