Netty 入門樣本

來源:互聯網
上載者:User

標籤:utf-8   system   它的   .net   eve   對象   stat   etc   equals   

服務端程式碼範例

import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioServerSocketChannel;public class TimeServer {    public void bind(int port) throws Exception {        //佈建服務端的NIO線程組        //NioEventLoopGroup是個線程組,它包含了一組NIO線程,專門用於網路事件的處理,        //實際上它們就是Reactor線程組。        //這裡建立兩個的原因是一個用於服務端接受用戶端的串連,另一個用於進行SocketChannel的網路讀寫。        EventLoopGroup bossGroup = new NioEventLoopGroup();        EventLoopGroup workerGroup = new NioEventLoopGroup();        try {            //建立ServerBootstrap對象,它是Netty用於啟動NIO服務端的輔助啟動類,目的是降低服務端的開發複雜度。            ServerBootstrap b = new ServerBootstrap();            //調用ServerBootstrap的group方法,將兩個NIO線程組當作入參傳遞到ServerBootstrap中。            //接著設定建立的Channel為NioServerSocketChannel,它的功能對應於JDK NIO類庫中的ServerSocketChannel類。            //然後配置NioServerSocketChannel的TCP參數,此處將它的backlog設定為1024,            //最後綁定I/O事件的處理類ChildChannelHandler,它的作用類似於Reactor模式中的handler類,            //主要用於處理網路I/O事件,例如記錄日誌、對訊息進行編解碼等。            b.group(bossGroup, workerGroup)                    .channel(NioServerSocketChannel.class)                    .option(ChannelOption.SO_BACKLOG, 1024)                    .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 {            //優雅退出,釋放線程池資源            //調用NIO線程組的shutdownGracefully進行優雅退出,它會釋放跟shutdownGracefully相關聯的資源。            bossGroup.shutdownGracefully();            workerGroup.shutdownGracefully();        }    }    private class ChildChannelHandler extends ChannelInitializer {        @Override        protected void initChannel(Channel channel) throws Exception {            channel.pipeline().addLast(new TimeServerHandler());        }    }    public static void main(String[] args) throws Exception {        new TimeServer().bind(8080);    }}import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;//TimeServerHandler繼承自ChannelHandlerAdapter,它用於對網路事件進行讀寫操作//通常我們只需要關注channelRead和exceptionCaught方法。public class TimeServerHandler extends ChannelHandlerAdapter {    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        //做類型轉換,將msg轉換成Netty的ByteBuf對象。        //ByteBuf類似於JDK中的java.nio.ByteBuffer 對象,不過它提供了更加強大和靈活的功能。        ByteBuf buf = (ByteBuf) msg;        //通過ByteBuf的readableBytes方法可以擷取緩衝區可讀的位元組數,        //根據可讀的位元組數建立byte數組        byte[] req = new byte[buf.readableBytes()];        //通過ByteBuf的readBytes方法將緩衝區中的位元組數組複製到建立的byte數組中        buf.readBytes(req);        //通過new String建構函式擷取請求訊息。        String body = new String(req, "UTF-8");        System.out.println("The time server receive order : " + body);        //如果是"QUERY TIME ORDER"則建立應答訊息,        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(                System.currentTimeMillis()).toString() : "BAD ORDER";        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());        //通過ChannelHandlerContext的write方法非同步發送應答訊息給用戶端。        ctx.write(resp);    }    @Override    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {        //調用了ChannelHandlerContext的flush方法,它的作用是將訊息發送隊列中的訊息寫入到SocketChannel中發送給對方。        //從效能角度考慮,為了防止頻繁地喚醒Selector進行訊息發送,        //Netty的write方法並不直接將訊息寫入SocketChannel中,調用write方法只是把待發送的訊息放到發送緩衝數組中,        //再通過調用flush方法,將發送緩衝區中的訊息全部寫到SocketChannel中。        ctx.flush();    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {        //當發生異常時,關閉ChannelHandlerContext,釋放和ChannelHandlerContext相關聯的控制代碼等資源。        ctx.close();    }}

用戶端程式碼範例:

import io.netty.bootstrap.Bootstrap;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioSocketChannel;public class TimeClient {    public void connect(int port, String host) throws Exception {        // 配置用戶端NIO線程組        //首先建立用戶端處理I/O讀寫的NioEventLoop Group線程組        EventLoopGroup group = new NioEventLoopGroup();        try {            //繼續建立用戶端輔助啟動類Bootstrap,隨後需要對其進行配置。            //與服務端不同的是,它的Channel需要設定為NioSocketChannel            //然後為其添加handler,此處為了簡單直接建立匿名內部類,實現initChannel方法,            //其作用是當建立NioSocketChannel成功之後,            //在初始化它的時候將它的ChannelHandler設定到ChannelPipeline中,用於處理網路I/O事件。            Bootstrap b = new Bootstrap();            b.group(group).channel(NioSocketChannel.class)                    .option(ChannelOption.TCP_NODELAY, true)                    .handler(new ChannelInitializer() {                        @Override                        protected void initChannel(Channel channel) throws Exception {                            channel.pipeline().addLast(new TimeClientHandler());                        }                    });            // 發起非同步串連操作            //用戶端啟動輔助類設定完成之後,調用connect方法發起非同步串連,            //然後調用同步方法等待串連成功。            ChannelFuture f = b.connect(host, port).sync();            // 等待用戶端鏈路關閉            //當用戶端串連關閉之後,用戶端主函數退出.            f.channel().closeFuture().sync();        } finally {            // 優雅退出,釋放NIO線程組            //在退出之前,釋放NIO線程組的資源。            group.shutdownGracefully();        }    }    public static void main(String[] args) throws Exception {        new TimeClient().connect(8080, "127.0.0.1");    }}import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;//重點關注三個方法:channelActive、channelRead和exceptionCaught。public class TimeClientHandler extends ChannelHandlerAdapter {    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) {        //發送查詢時間的指令給服務端        //調用ChannelHandlerContext的writeAndFlush方法將請求訊息發送給服務端。        ctx.writeAndFlush(firstMessage);    }    //當服務端返回應答訊息時,channelRead方法被調用    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {        //從Netty的ByteBuf中讀取並列印應答訊息。        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) {        // 釋放資源        //當發生異常時,列印異常日誌,釋放用戶端資源。        ctx.close();    }}

pom.xml

        <dependency>            <groupId>io.netty</groupId>            <artifactId>netty-all</artifactId>            <version>5.0.0.Alpha1</version>        </dependency>

 

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.