Netty服務端(源碼一)

來源:互聯網
上載者:User

標籤:其他   ini   用戶端   使用   style   cte   buffer   let   ada   

首先,整理NIO進行服務端開發的步驟:

  (1)建立ServerSocketChannel,配置它為非阻塞模式。

  (2)綁定監聽,配置TCP參數,backlog的大小。

  (3)建立一個獨立的I/O線程,用於輪詢多工器Selector。

  (4)建立Selector,將之前建立的ServerSocketChannel註冊到Selector上,監聽SelectionKeyACCEPT。

  (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,則說明還有資料沒有發送完成,需要繼續發送。  

 Netty時間伺服器服務端 TimeServer:

 1 package netty; 2  3 import io.netty.bootstrap.ServerBootstrap; 4 import io.netty.channel.ChannelFuture; 5 import io.netty.channel.ChannelInitializer; 6 import io.netty.channel.ChannelOption; 7 import io.netty.channel.EventLoopGroup; 8 import io.netty.channel.nio.NioEventLoopGroup; 9 import io.netty.channel.socket.SocketChannel;10 import io.netty.channel.socket.nio.NioServerSocketChannel;11 12 13 public class TimeServer {14     15     public void bind(int port) throws Exception{16         //佈建服務端的NIO線程組 一個用於服務端接收用戶端的串連,另一個用於進行SocketChannel的網路讀寫17         EventLoopGroup bossGroup = new NioEventLoopGroup();18         EventLoopGroup workerGroup = new NioEventLoopGroup();19         try{20             ServerBootstrap b = new ServerBootstrap();21             b.group(bossGroup,workerGroup)22             .channel(NioServerSocketChannel.class)23             .option(ChannelOption.SO_BACKLOG, 1024)24             .childHandler(new ChildChannelHandler());25             //綁定連接埠,同步等待成功26             ChannelFuture f = b.bind(port).sync();27             //等待伺服器監聽連接埠關閉28             f.channel().closeFuture().sync();29         }finally{30             //優雅退出,釋放線程池資源31             bossGroup.shutdownGracefully();32             workerGroup.shutdownGracefully();33         }34     }35     36     private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{37         protected void initChannel(SocketChannel arg0) throws Exception{38             arg0.pipeline().addLast(new TimeServerHandler());39         }40     }41 }

ServerBootstrap是Netty用於啟動NIO服務端的輔助類,目的是降低服務端的開發難度。

綁定childChannelHandler,其作用類似於Reactor模式中的handler類,主要用於處理網路I/O事件,例如記錄日誌、對訊息進行編解碼等。

使用bind綁定監聽連接埠,隨後,調用它的同步阻塞方法sync等待綁定操作完成,完成後Netty會返回一個ChannelFuture,主要用於非同步作業的通知回調。

 

Netty時間伺服器服務端 TimeServerHandler:

 1 package netty; 2  3 import java.io.IOException; 4 import io.netty.buffer.ByteBuf; 5 import io.netty.buffer.Unpooled; 6 import io.netty.channel.ChannelHandlerAdapter; 7 import io.netty.channel.ChannelHandlerContext; 8  9 public class TimeServerHandler extends ChannelHandlerAdapter{10     11     public void channelRead(ChannelHandlerContext ctx,Object msg) throws IOException{12         //將msg轉換成Netty的ByteBuf對象13         ByteBuf buf = (ByteBuf)msg;14         //將緩衝區中的位元組數組複製到建立的byte數組中,15         byte[] req = new byte[buf.readableBytes()];16         buf.readBytes(req);17         //擷取請求訊息18         String body = new String(req,"UTF-8");19         System.out.println("The time server receive order:" + body);20         //如果是"QUERY TIME ORDER"則建立應答訊息21         String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(22                 System.currentTimeMillis()).toString() : "BAD ORDER";23                 ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());24         //非同步發送應答訊息給用戶端25         ctx.write(resp);26     }27     28     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception{29         ctx.flush();30     }31     32     public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){33         ctx.close();34     }35 }

相比昨天原生的NIO服務端,代碼量大大減少。

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.