转载自http://lippeng.iteye.com/blog/1907279

Netty是什么?

本质:JBoss做的一个Jar包

目的:快速开发高性能、高可靠性的网络服务器和客户端程序

优点:提供异步的、事件驱动的网络应用程序框架和工具

通俗的说:一个好使的处理Socket的东东

如果没有Netty?

远古:java.net + java.io

近代:java.nio

其他:Mina,Grizzly

为什么不是Mina?

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

2、Mina将内核和一些特性的联系过于紧密,使得用户在不需要这些特性的时候无法脱离,相比下性能会有所下降,Netty解决了这个设计问题;

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

4、Netty更新周期更短,新版本的发布比较快;

5、它们的架构差别不大,Mina靠apache生存,而Netty靠jboss,和jboss的结合度非常高,Netty有对google protocal buf的支持,有更完整的ioc容器支持(spring,guice,jbossmc和osgi);

6、Netty比Mina使用起来更简单,Netty里你可以自定义的处理upstream events 或/和 downstream events,可以使用decoder和encoder来解码和编码发送内容;

7、Netty和Mina在处理UDP时有一些不同,Netty将UDP无连接的特性暴露出来;而Mina对UDP进行了高级层次的抽象,可以把UDP当成"面向连接"的协议,而要Netty做到这一点比较困难。

Netty的特性

设计

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

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

高度可定制的线程模型

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

性能

更好的吞吐量,低延迟

更省资源

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

安全

完整的SSL/TLS和STARTTLS的支持

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

健壮性

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

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

易用

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

简洁简单

仅信赖于JDK1.5

看例子吧!

Server端:

  1. package me.hello.netty;
  2. import org.jboss.netty.bootstrap.ServerBootstrap;
  3. import org.jboss.netty.channel.*;
  4. import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
  5. import org.jboss.netty.handler.codec.string.StringDecoder;
  6. import org.jboss.netty.handler.codec.string.StringEncoder;
  7. import java.net.InetSocketAddress;
  8. import java.util.concurrent.Executors;
  9. /**
  10. * God Bless You!
  11. * Author: Fangniude
  12. * Date: 2013-07-15
  13. */
  14. public class NettyServer {
  15. public static void main(String[] args) {
  16. ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
  17. // Set up the default event pipeline.
  18. bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
  19. @Override
  20. public ChannelPipeline getPipeline() throws Exception {
  21. return Channels.pipeline(new StringDecoder(), new StringEncoder(), new ServerHandler());
  22. }
  23. });
  24. // Bind and start to accept incoming connections.
  25. Channel bind = bootstrap.bind(new InetSocketAddress(8000));
  26. System.out.println("Server已经启动,监听端口: " + bind.getLocalAddress() + ", 等待客户端注册。。。");
  27. }
  28. private static class ServerHandler extends SimpleChannelHandler {
  29. @Override
  30. public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
  31. if (e.getMessage() instanceof String) {
  32. String message = (String) e.getMessage();
  33. System.out.println("Client发来:" + message);
  34. e.getChannel().write("Server已收到刚发送的:" + message);
  35. System.out.println("\n等待客户端输入。。。");
  36. }
  37. super.messageReceived(ctx, e);
  38. }
  39. @Override
  40. public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
  41. super.exceptionCaught(ctx, e);
  42. }
  43. @Override
  44. public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
  45. System.out.println("有一个客户端注册上来了。。。");
  46. System.out.println("Client:" + e.getChannel().getRemoteAddress());
  47. System.out.println("Server:" + e.getChannel().getLocalAddress());
  48. System.out.println("\n等待客户端输入。。。");
  49. super.channelConnected(ctx, e);
  50. }
  51. }
  52. }

客户端:

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

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

[转载] Netty的更多相关文章

  1. [转载] Netty源码分析

    转载自http://blog.csdn.net/kobejayandy/article/details/11836813 Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高 ...

  2. [转载] Netty教程

    转载自http://blog.csdn.net/kobejayandy/article/details/11493717 先啰嗦两句,如果你还不知道Netty是做什么的能做什么.那可以先简单的搜索了解 ...

  3. Netty组件理解(转载)

    转载的文章,写的非常好.   一.先纵览一下Netty,看看Netty都有哪些组件?        为了更好的理解和进一步深入Netty,我们先总体认识一下Netty用到的组件及它们在整个Netty架 ...

  4. netty对http协议解析原理解析(转载)

    本文主要介绍netty对http协议解析原理,着重讲解keep-alive,gzip,truncked等机制,详细描述了netty如何实现对http解析的高性能. 1 http协议 1.1 描述 标示 ...

  5. Netty系列之Netty可靠性分析--转载

    原文地址:http://www.infoq.com/cn/articles/netty-reliability 1. 背景 1.1. 宕机的代价 1.1.1. 电信行业 毕马威国际(KPMG Inte ...

  6. (三)Netty源码学习笔记之boss线程处理流程

    尊重原创,转载注明出处,原文地址:http://www.cnblogs.com/cishengchongyan/p/6160194.html  本文我们将先从NioEventLoop开始来学习服务端的 ...

  7. (二)Netty源码学习笔记之服务端启动

    尊重原创,转载注明出处,原文地址:http://www.cnblogs.com/cishengchongyan/p/6129971.html  本文将不会对netty中每个点分类讲解,而是一个服务端启 ...

  8. (一)Netty源码学习笔记之概念解读

    尊重原创,转载注明出处,原文地址:http://www.cnblogs.com/cishengchongyan/p/6121065.html  博主最近在做网络相关的项目,因此有契机学习netty,先 ...

  9. Netty(五)序列化protobuf在netty中的使用

    protobuf是google序列化的工具,主要是把数据序列化成二进制的数据来传输用的.它主要优点如下: 1.性能好,效率高: 2.跨语言(java自带的序列化,不能跨语言) protobuf参考文档 ...

随机推荐

  1. HDU1789 Doing Homework again

    基础单调队列: #include<cstdio> #include<cstdlib> #include<iostream> #include<algorith ...

  2. Winform常用的一些功能收集(持续更新)

    #region progressBar实时显示进度 private void button1_Click(object sender, EventArgs e) { int i = 10000; pr ...

  3. 笨鸟先飞之ASP.NET MVC系列之过滤器(03动作过滤器过滤器)

    概念介绍 动作过滤器应该是我们平常工作中需要用到最多的过滤器了,动作过滤器,主要在我们的动作方法执行前后执行. 如果我们需要创建动作过滤器需要实现IActionFilter接口. 我们看到该接口里有两 ...

  4. 解析 .Net Core 注入 (1) 注册服务

    在学习 Asp.Net Core 的过程中,注入可以说是无处不在,对于 .Net Core 来说,它是独立的一个程序集,没有复杂的依赖项和配置文件,所以对于学习 Asp.Net Core 源码的朋友来 ...

  5. word2vec 数学原理

    word2vec 是 Google 于 2013 年推出的一个用于获取词向量的开源工具包.我们在项目中多次使用到它,但囿于时间关系,一直没仔细探究其背后的原理. 网络上 <word2vec 中的 ...

  6. ThreadPoolExecutor系列<三、ThreadPoolExecutor 源码解析>

    本文系作者原创,转载请注明出处:http://www.cnblogs.com/further-further-further/p/7681826.html 在源码解析前,需要先理清线程池控制的运行状态 ...

  7. (转)HTTP1.0和HTTP1.1的区别

    原文出自:http://www.cnblogs.com/gofighting/p/5421890.html 1.HTTP 1.1支持长连接(PersistentConnection)和请求的流水线(P ...

  8. IDEA + Maven + JavaWeb项目搭建

    前言:在网上一直没找到一个完整的IDEA+Maven+Web项目搭建,对于IDEA和Maven初学者来说,这个过程简单但是非常痛苦的,对中间的某些步骤不是很理解,导致操作错误,从而项目发布不成功,一直 ...

  9. LeetCode 205. Isomorphic Strings (同构字符串)

    Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the chara ...

  10. 最详细的浏览器css hack

    注意点: 网上很多资料中常常把!important也作为一个hack手段,其实这是一个误区.!important常常被我们用来更改样式,而不是兼容hack.造成这个误区的原因是IE6在某些情况下不主动 ...