Netty學習之用戶端建立,netty用戶端建立

來源:互聯網
上載者:User

Netty學習之用戶端建立,netty用戶端建立
一、用戶端開發時序圖

  

  圖片來源:Netty權威指南(第2版)

二、Netty用戶端開發步驟

  使用Netty進行用戶端開發主要有以下幾個步驟:

  1、使用者線程建立Bootstrap
Bootstrap b = new Bootstrap();

  Bootstrap是Socket用戶端建立工具類,通過API設定建立用戶端相關的參數,非同步發起用戶端串連。

  2、建立處理用戶端串連、IO讀寫的Reactor線程組NioEventLoopGroup
EventLoopGroup group = new NioEventLoopGroup();
  3、通過Bootstrap的ChannelFactory和使用者指定的Channel類型建立用於用戶端串連的NioSocketChannel
b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)

  此處的NioSocketChannel類似於Java NIO提供的SocketChannel。

  4、建立預設的channel Handler pipeline
b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>()  {       @Override       public void initChannel(SocketChannel ch) throws Exception       {         ch.pipeline().addLast(new HelloClientHandler());        }  });

  用於調度和執行網路事件。

  5、非同步發起TCP串連
 // 發起非同步串連操作 ChannelFuture f = b.connect(host, port).sync();

  SocketChannel執行connect()操作後有以下三種結果:

  • 串連成功,然會true;
  • 暫時沒有串連上,伺服器端沒有返回ACK應答,串連結果不確定,返回false。此種結果下,需要將NioSocketChannel中的selectionKey設定為OP_CONNECT,監聽串連結果;
  • 接連失敗,直接拋出I/O異常
  6、由多工器在I/O中輪詢個Channel,處理串連結果  7、如果串連成功,設定Future結果,發送串連成功事件,觸發ChannelPipeline執行  8、由ChannelPipeline調度執行系統和使用者的ChannelHandler,執行商務邏輯三、Netty用戶端開發範例程式碼

  需求:用戶端端實現,串連伺服器端,並向伺服器端發送hello Netty。(註:本代碼使用的netty是netty-all-5.0.0.Alpha1-sources.jar版本)

  伺服器端代碼見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 HelloClient{    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                        public void initChannel(SocketChannel ch) throws Exception                        {                            ch.pipeline().addLast(new HelloClientHandler());                        }                    });            // 發起非同步串連操作            ChannelFuture f = b.connect(host, port).sync();            // 等待用戶端鏈路關閉            f.channel().closeFuture().sync();        } finally        {            group.shutdownGracefully();        }    }    public static void main(String[] args) throws Exception    {        int port = 8080;        new HelloClient().connect(port, "127.0.0.1");    }}
import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;public class HelloClientHandler  extends ChannelHandlerAdapter{    private final ByteBuf message;        public HelloClientHandler()    {        byte[] req="hello Netty".getBytes();        message=Unpooled.buffer(req.length);        message.writeBytes(req);    }    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception    {        ctx.writeAndFlush(message);    }        @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception    {        ctx.close();    }}

  程式運行結果:

  

四、參考資料

  1、Netty權威指南

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.