paulwong

          Netty是什么?

          本質(zhì):JBoss做的一個(gè)Jar包

           

          目的:快速開(kāi)發(fā)高性能、高可靠性的網(wǎng)絡(luò)服務(wù)器和客戶(hù)端程序

           

          優(yōu)點(diǎn):提供異步的、事件驅(qū)動(dòng)的網(wǎng)絡(luò)應(yīng)用程序框架和工具

           

          通俗的說(shuō):一個(gè)好使的處理Socket的東東

           

           

          如果沒(méi)有Netty?

           

          遠(yuǎn)古:java.net + java.io

           

          近代:java.nio

           

          其他:Mina,Grizzly

           

          為什么不是Mina?

           

          1、都是Trustin Lee的作品,Netty更晚;

          2、Mina將內(nèi)核和一些特性的聯(lián)系過(guò)于緊密,使得用戶(hù)在不需要這些特性的時(shí)候無(wú)法脫離,相比下性能會(huì)有所下降,Netty解決了這個(gè)設(shè)計(jì)問(wèn)題;

          3、Netty的文檔更清晰,很多Mina的特性在Netty里都有;

          4、Netty更新周期更短,新版本的發(fā)布比較快;

          5、它們的架構(gòu)差別不大,Mina靠apache生存,而Netty靠jboss,和jboss的結(jié)合度非常高,Netty有對(duì)google protocal buf的支持,有更完整的ioc容器支持(spring,guice,jbossmc和osgi);

          6、Netty比Mina使用起來(lái)更簡(jiǎn)單,Netty里你可以自定義的處理upstream events 或/和 downstream events,可以使用decoder和encoder來(lái)解碼和編碼發(fā)送內(nèi)容;

          7、Netty和Mina在處理UDP時(shí)有一些不同,Netty將UDP無(wú)連接的特性暴露出來(lái);而Mina對(duì)UDP進(jìn)行了高級(jí)層次的抽象,可以把UDP當(dāng)成"面向連接"的協(xié)議,而要Netty做到這一點(diǎn)比較困難。

           

           

          Netty的特性

           

          設(shè)計(jì)

          統(tǒng)一的API,適用于不同的協(xié)議(阻塞和非阻塞)

          基于靈活、可擴(kuò)展的事件驅(qū)動(dòng)模型

          高度可定制的線程模型

          可靠的無(wú)連接數(shù)據(jù)Socket支持(UDP)

           

          性能

          更好的吞吐量,低延遲

          更省資源

          盡量減少不必要的內(nèi)存拷貝

           

          安全

          完整的SSL/TLS和STARTTLS的支持

          能在Applet與Android的限制環(huán)境運(yùn)行良好

           

          健壯性

          不再因過(guò)快、過(guò)慢或超負(fù)載連接導(dǎo)致OutOfMemoryError

          不再有在高速網(wǎng)絡(luò)環(huán)境下NIO讀寫(xiě)頻率不一致的問(wèn)題

           

          易用

          完善的JavaDoc,用戶(hù)指南和樣例

          簡(jiǎn)潔簡(jiǎn)單

          僅信賴(lài)于JDK1.5

           

          看例子吧!

           

          Server端:

           

          Java代碼  收藏代碼
          1. package me.hello.netty;  
          2.   
          3. import org.jboss.netty.bootstrap.ServerBootstrap;  
          4. import org.jboss.netty.channel.*;  
          5. import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;  
          6. import org.jboss.netty.handler.codec.string.StringDecoder;  
          7. import org.jboss.netty.handler.codec.string.StringEncoder;  
          8.   
          9. import java.net.InetSocketAddress;  
          10. import java.util.concurrent.Executors;  
          11.   
          12. /** 
          13.  * God Bless You! 
          14.  * Author: Fangniude 
          15.  * Date: 2013-07-15 
          16.  */  
          17. public class NettyServer {  
          18.     public static void main(String[] args) {  
          19.         ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));  
          20.   
          21.         // Set up the default event pipeline.  
          22.         bootstrap.setPipelineFactory(new ChannelPipelineFactory() {  
          23.             @Override  
          24.             public ChannelPipeline getPipeline() throws Exception {  
          25.                 return Channels.pipeline(new StringDecoder(), new StringEncoder(), new ServerHandler());  
          26.             }  
          27.         });  
          28.   
          29.         // Bind and start to accept incoming connections.  
          30.         Channel bind = bootstrap.bind(new InetSocketAddress(8000));  
          31.         System.out.println("Server已經(jīng)啟動(dòng),監(jiān)聽(tīng)端口: " + bind.getLocalAddress() + ", 等待客戶(hù)端注冊(cè)。。。");  
          32.     }  
          33.   
          34.     private static class ServerHandler extends SimpleChannelHandler {  
          35.         @Override  
          36.         public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {  
          37.             if (e.getMessage() instanceof String) {  
          38.                 String message = (String) e.getMessage();  
          39.                 System.out.println("Client發(fā)來(lái):" + message);  
          40.   
          41.                 e.getChannel().write("Server已收到剛發(fā)送的:" + message);  
          42.   
          43.                 System.out.println("\n等待客戶(hù)端輸入。。。");  
          44.             }  
          45.   
          46.             super.messageReceived(ctx, e);  
          47.         }  
          48.   
          49.         @Override  
          50.         public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {  
          51.             super.exceptionCaught(ctx, e);  
          52.         }  
          53.   
          54.         @Override  
          55.         public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {  
          56.             System.out.println("有一個(gè)客戶(hù)端注冊(cè)上來(lái)了。。。");  
          57.             System.out.println("Client:" + e.getChannel().getRemoteAddress());  
          58.             System.out.println("Server:" + e.getChannel().getLocalAddress());  
          59.             System.out.println("\n等待客戶(hù)端輸入。。。");  
          60.             super.channelConnected(ctx, e);  
          61.         }  
          62.     }  
          63. }  

           

          客戶(hù)端:

           

          Java代碼  收藏代碼
          1. package me.hello.netty;  
          2.   
          3. import org.jboss.netty.bootstrap.ClientBootstrap;  
          4. import org.jboss.netty.channel.*;  
          5. import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;  
          6. import org.jboss.netty.handler.codec.string.StringDecoder;  
          7. import org.jboss.netty.handler.codec.string.StringEncoder;  
          8.   
          9. import java.io.BufferedReader;  
          10. import java.io.InputStreamReader;  
          11. import java.net.InetSocketAddress;  
          12. import java.util.concurrent.Executors;  
          13.   
          14. /** 
          15.  * God Bless You! 
          16.  * Author: Fangniude 
          17.  * Date: 2013-07-15 
          18.  */  
          19. public class NettyClient {  
          20.   
          21.     public static void main(String[] args) {  
          22.         // Configure the client.  
          23.         ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));  
          24.   
          25.         // Set up the default event pipeline.  
          26.         bootstrap.setPipelineFactory(new ChannelPipelineFactory() {  
          27.             @Override  
          28.             public ChannelPipeline getPipeline() throws Exception {  
          29.                 return Channels.pipeline(new StringDecoder(), new StringEncoder(), new ClientHandler());  
          30.             }  
          31.         });  
          32.   
          33.         // Start the connection attempt.  
          34.         ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8000));  
          35.   
          36.         // Wait until the connection is closed or the connection attempt fails.  
          37.         future.getChannel().getCloseFuture().awaitUninterruptibly();  
          38.   
          39.         // Shut down thread pools to exit.  
          40.         bootstrap.releaseExternalResources();  
          41.     }  
          42.   
          43.     private static class ClientHandler extends SimpleChannelHandler {  
          44.         private BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));  
          45.   
          46.         @Override  
          47.         public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {  
          48.             if (e.getMessage() instanceof String) {  
          49.                 String message = (String) e.getMessage();  
          50.                 System.out.println(message);  
          51.   
          52.                 e.getChannel().write(sin.readLine());  
          53.   
          54.                 System.out.println("\n等待客戶(hù)端輸入。。。");  
          55.             }  
          56.   
          57.             super.messageReceived(ctx, e);  
          58.         }  
          59.   
          60.         @Override  
          61.         public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {  
          62.             System.out.println("已經(jīng)與Server建立連接。。。。");  
          63.             System.out.println("\n請(qǐng)輸入要發(fā)送的信息:");  
          64.             super.channelConnected(ctx, e);  
          65.   
          66.             e.getChannel().write(sin.readLine());  
          67.         }  
          68.     }  
          69. }  

           

          Netty整體架構(gòu)



           

          Netty組件

           

          ChannelFactory

          Boss

          Worker

          Channel

          ChannelEvent

          Pipeline

          ChannelContext

          Handler

          Sink

           

          Server端核心類(lèi)

          NioServerSocketChannelFactory

          NioServerBossPool 

          NioWorkerPool

          NioServerBoss

          NioWorker

          NioServerSocketChannel

          NioAcceptedSocketChannel

          DefaultChannelPipeline

          NioServerSocketPipelineSink

          Channels

           

           

          ChannelFactory

          Channel工廠,很重要的類(lèi)

          保存啟動(dòng)的相關(guān)參數(shù)

           

          NioServerSocketChannelFactory

          NioClientSocketChannelFactory

          NioDatagramChannelFactory

           

          這是Nio的,還有Oio和Local的

           

           

          SelectorPool

           

          Selector的線程池

           

          NioServerBossPool 默認(rèn)線程數(shù):1

          NioClientBossPool      1

          NioWorkerPool      2 * Processor

          NioDatagramWorkerPool

           

           

          Selector

           

          選擇器,很核心的組件

           

          NioServerBoss

          NioClientBoss

          NioWorker

          NioDatagramWorker

           

           

          Channel

           

          通道

           

          NioServerSocketChannel

          NioClientSocketChannel

          NioAcceptedSocketChannel

          NioDatagramChannel

           

          Sink

          負(fù)責(zé)和底層的交互

          如bind,Write,Close等

           

          NioServerSocketPipelineSink

          NioClientSocketPipelineSink

          NioDatagramPipelineSink

           

          Pipeline

          負(fù)責(zé)維護(hù)所有的Handler

           

          ChannelContext

          一個(gè)Channel一個(gè),是Handler和Pipeline的中間件

           

          Handler

          對(duì)Channel事件的處理器

           

           

          ChannelPipeline

           



           

           

           

          優(yōu)秀的設(shè)計(jì)----事件驅(qū)動(dòng)



           

           

          優(yōu)秀的設(shè)計(jì)----線程模型



           

          注意事項(xiàng)

           

          解碼時(shí)的Position

           

          Channel的關(guān)閉

           

          更多Handler

           

           

          Channel的關(guān)閉

           

          用完的Channel,可以直接關(guān)閉;

          1、ChannelFuture加Listener

          2、writeComplete

           

          一段時(shí)間沒(méi)用,也可以關(guān)閉

          TimeoutHandler

          posted on 2016-04-12 15:19 paulwong 閱讀(889) 評(píng)論(0)  編輯  收藏 所屬分類(lèi): NETTY

          主站蜘蛛池模板: 阳高县| 永胜县| 正蓝旗| 开阳县| 蓝田县| 隆安县| 拜城县| 鹤壁市| 临朐县| 札达县| 兴城市| 泸溪县| 宁阳县| 榆林市| 玛曲县| 江山市| 钦州市| 星座| 苏尼特右旗| 定陶县| 马尔康县| 龙胜| 行唐县| 丰镇市| 宝应县| 本溪市| 安平县| 霸州市| 陇南市| 思南县| 大田县| 都安| 芦山县| 饶河县| 大化| 金乡县| 塔城市| 郁南县| 兰溪市| 宁明县| 库伦旗|