Netty:JBOSS的 JAVA NIO开发开源框架

Netty是由 JBOSS提供的一个 java开源框架。Netty提供异步的、 事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的 网络服务器和客户端程序。
也就是说,Netty 是一个基于NIO的客户,服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户, 服务端应用。Netty相当简化和流线化了网络应用的编程开发过程,例如,TCP和UDP的socket服务开发。
“快速”和“简单”并不意味着会让你的最终应用产生维护性或性能上的问题。Netty 是一个吸收了多种协议的实现经验,这些协议包括FTP,SMTP,HTTP,各种二进制,文本协议,并经过相当精心设计的项目,最终,Netty 成功的找到了一种方式,在保证易于开发的同时还保证了其应用的性能,稳定性和伸缩性。

Netty的特性

设计

统一的API,适用于不同的协议(阻塞和非阻塞)

基于灵活、可扩展的事件驱动模型

高度可定制的线程模型

可靠的无连接数据Socket支持(UDP)

性能

更好的吞吐量,低延迟

更省资源

尽量减少不必要的内存拷贝

安全

完整的SSL/TLS和STARTTLS的支持

能在Applet与Android的限制环境运行良好

健壮性

不再因过快、过慢或超负载连接导致OutOfMemoryError

不再有在高速网络环境下NIO读写频率不一致的问题

易用

完善的JavaDoc,用户指南和样例

简洁简单

仅信赖于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已经启动,监听端口: " + bind.getLocalAddress() + ", 等待客户端注册。。。");   
  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发来:" + message);   
  40.   
  41.                 e.getChannel().write("Server已收到刚发送的:" + message);   
  42.   
  43.                 System.out.println("\n等待客户端输入。。。");   
  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("有一个客户端注册上来了。。。");   
  57.             System.out.println("Client:" + e.getChannel().getRemoteAddress());   
  58.             System.out.println("Server:" + e.getChannel().getLocalAddress());   
  59.             System.out.println("\n等待客户端输入。。。");   
  60.             super.channelConnected(ctx, e);   
  61.         }   
  62.     }   
  63. }  

客户端:

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等待客户端输入。。。");   
  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("已经与Server建立连接。。。。");   
  63.             System.out.println("\n请输入要发送的信息:");   
  64.             super.channelConnected(ctx, e);   
  65.   
  66.             e.getChannel().write(sin.readLine());   
  67.         }   
  68.     }   
  69. }  

Netty整体架构


 

Netty组件

 

ChannelFactory

Boss

Worker

Channel

ChannelEvent

Pipeline

ChannelContext

Handler

Sink

 

Server端核心类

NioServerSocketChannelFactory

NioServerBossPool 

NioWorkerPool

NioServerBoss

NioWorker

NioServerSocketChannel

NioAcceptedSocketChannel

DefaultChannelPipeline

NioServerSocketPipelineSink

Channels


ChannelFactory

Channel工厂,很重要的类

保存启动的相关参数

NioServerSocketChannelFactory

NioClientSocketChannelFactory

NioDatagramChannelFactory

 

这是Nio的,还有Oio和Local的

SelectorPool

Selector的线程池

NioServerBossPool 默认线程数:1

NioClientBossPool      1

NioWorkerPool      2 * Processor

NioDatagramWorkerPool

 

Selector

选择器,很核心的组件

NioServerBoss

NioClientBoss

NioWorker

NioDatagramWorker

Channel

通道

NioServerSocketChannel

NioClientSocketChannel

NioAcceptedSocketChannel

NioDatagramChannel

 

Sink

负责和底层的交互

如bind,Write,Close等

 

NioServerSocketPipelineSink

NioClientSocketPipelineSink

NioDatagramPipelineSink

 

Pipeline

负责维护所有的Handler

 

ChannelContext

一个Channel一个,是Handler和Pipeline的中间件

 

Handler

对Channel事件的处理器

 

ChannelPipeline


 

 

 

优秀的设计----事件驱动



 

 

优秀的设计----线程模型



 

注意事项

 

解码时的Position

 

Channel的关闭

 

更多Handler

 

 

Channel的关闭

 

用完的Channel,可以直接关闭;

1、ChannelFuture加Listener

2、writeComplete

 

一段时间没用,也可以关闭

TimeoutHandler

 

 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值