Netty(一)——Netty入門程序


轉載請注明出處:http://www.cnblogs.com/Joanna-Yan/p/7447618.html

有興趣的可先了解下:4種I/O的對比與選型

主要內容包括:

  • Netty開發環境的搭建
  • 服務端程序TimeServer開發
  • 客戶端程序TimeClient開發
  • 時間服務器的運行和調試

1.Netty開發環境的搭建

  前提:電腦上已經安裝了JDK1.7並配置了JDK的環境變量path。

  從Netty官網下載Netty最新安裝包,解壓。

  這時會發現里面包含了各個模塊的.jar包和源碼,由於我們直接以二進制類庫的方式使用Netty,所以只需要netty-all-4.1.15.Final.jar即可。

  新建Java工程,引入netty-all-4.1.15.Final.jar。

2.Netty服務端開發

  在使用Netty開發TimeServer之前,先回顧一下使用NIO進行服務端開發的步驟。

  1. 創建ServerSocketChannel,配置它為非阻塞模式;
  2. 綁定監聽,配置TCP參數,例如backlog大小;
  3. 創建一個獨立的I/O線程,用於輪詢多路復用器Selector;
  4. 創建Selector,將之前創建的ServerSocketChannel注冊到Selector上,監聽SelectionKey.ACCEPT;
  5. 啟動I/O線程,在循環體中執行Selector.select()方法,輪詢就緒的Channel;
  6. 當輪詢到了就緒狀態的Channel時,需要對其進行判斷,如果是OP_ACCEPT狀態,說明是新的客戶端接入,則調用ServerSocketChannel.accept()方法接受新的客戶端;
  7. 設置新接入的客戶端鏈路SocketChannel為非阻塞模式,配置其他的一些TCP參數;
  8. 將SocketChannel注冊到Selector,監聽OP_READ操作位;
  9. 如果輪詢的Channel為OP_READ,則說明SocketChannel中有新的就緒的數據包需要讀取,則構造ByteBuffer對象,讀取數據包;
  10. 如果輪詢的Channel為OP_WRITE,說明數據還沒有發送完成,需要繼續發送。

  一個簡單的NIO服務端程序,如果需要我們直接使用JDK的NIO類庫進行開發,竟然需要經過繁瑣的十多步操作才能完成最基本的消息讀取和發送,這也是我們選擇Netty等NIO框架的原因了,下面我們看看使用Netty是如何輕松搞定服務端開發的。

package joanna.yan.netty;

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;

public class TimeServer {
    
    public static void main(String[] args) throws Exception {
        int port=9090;
        if(args!=null&&args.length>0){
            try {
                port=Integer.valueOf(args[0]);
            } catch (Exception e) {
                // 采用默認值
            }
        }
        new TimeServer().bind(port);
    }
    
    public void bind(int port) throws Exception{
        /*
         * 配置服務端的NIO線程組,它包含了一組NIO線程,專門用於網絡事件的處理,實際上它們就是Reactor線程組。
         * 這里創建兩個的原因:一個用於服務端接受客戶端的連接,
         * 另一個用於進行SocketChannel的網絡讀寫。
         */
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        EventLoopGroup workerGroup=new NioEventLoopGroup();
        try {
            //ServerBootstrap對象,Netty用於啟動NIO服務端的輔助啟動類,目的是降低服務端的開發復雜度。
            ServerBootstrap b=new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .option(ChannelOption.SO_BACKLOG, 1024)
             /*
              * 綁定I/O事件的處理類ChildChannelHandler,它的作用類似於Reactor模式中的handler類,
              * 主要用於處理網絡I/O事件,例如:記錄日志、對消息進行編解碼等。
              */
             .childHandler(new ChildChannelHandler());
            /*
             * 綁定端口,同步等待成功(調用它的bind方法綁定監聽端口,隨后,調用它的同步阻塞方法sync等待綁定操作完成。
             * 完成之后Netty會返回一個ChannelFuture,它的功能類似於JDK的java.util.concurrent.Future,
             * 主要用於異步操作的通知回調。)
             */
            ChannelFuture f=b.bind(port).sync();
            
            //等待服務端監聽端口關閉(使用f.channel().closeFuture().sync()方法進行阻塞,等待服務端鏈路關閉之后main函數才退出。)
            f.channel().closeFuture().sync();
        }finally{
            //優雅退出,釋放線程池資源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    
    private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{

        @Override
        protected void initChannel(SocketChannel arg0) throws Exception {
            arg0.pipeline().addLast(new TimeServerHandler());
        }      
    }
}
package joanna.yan.netty;

import java.sql.Date;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 用於對網絡事件進行讀寫操作
 * @author Joanna.Yan
 * @date 2017年11月8日下午4:15:13
 */
//public class TimeServerHandler extends ChannelHandlerAdapter{//已摒棄
public class TimeServerHandler extends ChannelInboundHandlerAdapter{

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        //ByteBuf類似於JDK中的java.nio.ByteBuffer對象,不過它提供了更加強大和靈活的功能。
        ByteBuf buf=(ByteBuf) msg;
        byte[] req=new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body=new String(req, "UTF-8");
        System.out.println("The time server receive order : "+body);
        String currentTime="QUERY TIME ORDER".equalsIgnoreCase(body) ? new 
                Date(System.currentTimeMillis()).toString() : "BAD ORDER";
        ByteBuf resp=Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.write(resp);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        /*
         * ctx.flush();將消息發送隊列中的消息寫入到SocketChannel中發送給對方。
         * 從性能角度考慮,為了防止頻繁地喚醒Selector進行消息發送,Netty的write方法並不直接將消息寫入SocketChannel中,
         * 調用write方法只是把待發送的消息放到發送緩沖數組中,再通過調用flush方法,將發送緩沖區中的消息全部寫到SocketChannel中。
         */
        ctx.flush();
    }

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

3.Netty客戶端開發

package joanna.yan.netty;

import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;

public class TimeClient {
    public static void main(String[] args) throws Exception {
        int port=9019;
        if(args!=null&&args.length>0){
            try {
                port=Integer.valueOf(args[0]);
            } catch (Exception e) {
                // 采用默認值
            }
        }
        new TimeClient().connect(port, "127.0.0.1");
    }
    
    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
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new TimeClientHandler());
                }
            });
            
            //發起異步連接操作
            ChannelFuture f=b.connect(host, port).sync();
            
            //等待客戶端鏈路關閉
            f.channel().closeFuture().sync();
        }finally{
            //優雅退出,釋放NIO線程組
            group.shutdownGracefully();
        }
    }
}
package joanna.yan.netty;

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;
import io.netty.channel.SimpleChannelInboundHandler;

//public class TimeClientHandler extends ChannelHandlerAdapter{//已摒棄
public class TimeClientHandler extends ChannelInboundHandlerAdapter{
    private static final Logger logger=Logger.getLogger(TimeClientHandler.class.getName());
    private final ByteBuf firstMessage;
    
    public TimeClientHandler(){
        byte[] req="QUERY TIME ORDER".getBytes();
        firstMessage=Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
    }

    /**
     * 當客戶端和服務端TCP鏈路建立成功之后,Netty的NIO線程會調用channelActive方法,
     * 發送查詢時間的指令給服務端。
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //將請求信息發送給服務端
        ctx.writeAndFlush(firstMessage);
    }

    /**
     * 當服務端返回應答消息時調用channelRead方法
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        ByteBuf buf=(ByteBuf) msg;
        byte[] req=new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body=new String(req, "UTF-8");
        System.out.println("Now is :"+body);
    }
    
    /**
     * 發生異常是,打印異常日志,釋放客戶端資源。
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        //釋放資源
        logger.warning("Unexpected exception from downstream : "+cause.getMessage());
        ctx.close();
    }  
}

 ChannelInboundHandlerAdapter和SimpleChannelInboundHandler的使用區分:

   ChannelInboundHandlerAdapter是普通類,而SimpleChannelInboundHandler<T>是抽象類,繼承SimpleChannelInboundHandler的類必須實現channelRead0方法;SimpleChannelInboundHandler<T>有一個重要特性,就是消息被讀取后,會自動釋放資源,常見的IM聊天軟件的機制就類似這種。而且SimpleChannelInboundHandler類是繼承了ChannelInboundHandlerAdapter類,重寫了channelRead()方法,並新增抽象類。絕大部分場景都可以用ChannelInboundHandlerAdapter來處理。

4.運行與調試

  服務端運行結果:

  客戶端運行結果:

 

  運行結果正確。可以發現,通過Netty開發的NIO服務端和客戶端非常簡單,短短幾十行代碼就能完成之前NIO程序需要幾百行才能完成的功能。基於Netty的應用開發不但API使用簡單、開發模式固定,而且擴展性和定制性非常好,后面,會通過更多應用來介紹Netty的強大功能。

  需要指出的是,本示例沒有考慮讀半包的處理,對於功能演示或者測試,上述程序沒有問題,但是稍加改造進行性能或者壓力測試,它就不能正確地工作了。后面我們會給出能夠正確處理半包消息的應用實例。

Netty(二)——TCP粘包/拆包

 如果此文對您有幫助,微信打賞我一下吧~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM