[转载] Netty
转载自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端:
- package me.hello.netty;
- import org.jboss.netty.bootstrap.ServerBootstrap;
- import org.jboss.netty.channel.*;
- import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
- import org.jboss.netty.handler.codec.string.StringDecoder;
- import org.jboss.netty.handler.codec.string.StringEncoder;
- import java.net.InetSocketAddress;
- import java.util.concurrent.Executors;
- /**
- * God Bless You!
- * Author: Fangniude
- * Date: 2013-07-15
- */
- public class NettyServer {
- public static void main(String[] args) {
- ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
- // Set up the default event pipeline.
- bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
- @Override
- public ChannelPipeline getPipeline() throws Exception {
- return Channels.pipeline(new StringDecoder(), new StringEncoder(), new ServerHandler());
- }
- });
- // Bind and start to accept incoming connections.
- Channel bind = bootstrap.bind(new InetSocketAddress(8000));
- System.out.println("Server已经启动,监听端口: " + bind.getLocalAddress() + ", 等待客户端注册。。。");
- }
- private static class ServerHandler extends SimpleChannelHandler {
- @Override
- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
- if (e.getMessage() instanceof String) {
- String message = (String) e.getMessage();
- System.out.println("Client发来:" + message);
- e.getChannel().write("Server已收到刚发送的:" + message);
- System.out.println("\n等待客户端输入。。。");
- }
- super.messageReceived(ctx, e);
- }
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
- super.exceptionCaught(ctx, e);
- }
- @Override
- public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
- System.out.println("有一个客户端注册上来了。。。");
- System.out.println("Client:" + e.getChannel().getRemoteAddress());
- System.out.println("Server:" + e.getChannel().getLocalAddress());
- System.out.println("\n等待客户端输入。。。");
- super.channelConnected(ctx, e);
- }
- }
- }
客户端:
- package me.hello.netty;
- import org.jboss.netty.bootstrap.ClientBootstrap;
- import org.jboss.netty.channel.*;
- import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
- import org.jboss.netty.handler.codec.string.StringDecoder;
- import org.jboss.netty.handler.codec.string.StringEncoder;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.net.InetSocketAddress;
- import java.util.concurrent.Executors;
- /**
- * God Bless You!
- * Author: Fangniude
- * Date: 2013-07-15
- */
- public class NettyClient {
- public static void main(String[] args) {
- // Configure the client.
- ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
- // Set up the default event pipeline.
- bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
- @Override
- public ChannelPipeline getPipeline() throws Exception {
- return Channels.pipeline(new StringDecoder(), new StringEncoder(), new ClientHandler());
- }
- });
- // Start the connection attempt.
- ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8000));
- // Wait until the connection is closed or the connection attempt fails.
- future.getChannel().getCloseFuture().awaitUninterruptibly();
- // Shut down thread pools to exit.
- bootstrap.releaseExternalResources();
- }
- private static class ClientHandler extends SimpleChannelHandler {
- private BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
- @Override
- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
- if (e.getMessage() instanceof String) {
- String message = (String) e.getMessage();
- System.out.println(message);
- e.getChannel().write(sin.readLine());
- System.out.println("\n等待客户端输入。。。");
- }
- super.messageReceived(ctx, e);
- }
- @Override
- public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
- System.out.println("已经与Server建立连接。。。。");
- System.out.println("\n请输入要发送的信息:");
- super.channelConnected(ctx, e);
- e.getChannel().write(sin.readLine());
- }
- }
- }
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的更多相关文章
- [转载] Netty源码分析
转载自http://blog.csdn.net/kobejayandy/article/details/11836813 Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高 ...
- [转载] Netty教程
转载自http://blog.csdn.net/kobejayandy/article/details/11493717 先啰嗦两句,如果你还不知道Netty是做什么的能做什么.那可以先简单的搜索了解 ...
- Netty组件理解(转载)
转载的文章,写的非常好. 一.先纵览一下Netty,看看Netty都有哪些组件? 为了更好的理解和进一步深入Netty,我们先总体认识一下Netty用到的组件及它们在整个Netty架 ...
- netty对http协议解析原理解析(转载)
本文主要介绍netty对http协议解析原理,着重讲解keep-alive,gzip,truncked等机制,详细描述了netty如何实现对http解析的高性能. 1 http协议 1.1 描述 标示 ...
- Netty系列之Netty可靠性分析--转载
原文地址:http://www.infoq.com/cn/articles/netty-reliability 1. 背景 1.1. 宕机的代价 1.1.1. 电信行业 毕马威国际(KPMG Inte ...
- (三)Netty源码学习笔记之boss线程处理流程
尊重原创,转载注明出处,原文地址:http://www.cnblogs.com/cishengchongyan/p/6160194.html 本文我们将先从NioEventLoop开始来学习服务端的 ...
- (二)Netty源码学习笔记之服务端启动
尊重原创,转载注明出处,原文地址:http://www.cnblogs.com/cishengchongyan/p/6129971.html 本文将不会对netty中每个点分类讲解,而是一个服务端启 ...
- (一)Netty源码学习笔记之概念解读
尊重原创,转载注明出处,原文地址:http://www.cnblogs.com/cishengchongyan/p/6121065.html 博主最近在做网络相关的项目,因此有契机学习netty,先 ...
- Netty(五)序列化protobuf在netty中的使用
protobuf是google序列化的工具,主要是把数据序列化成二进制的数据来传输用的.它主要优点如下: 1.性能好,效率高: 2.跨语言(java自带的序列化,不能跨语言) protobuf参考文档 ...
随机推荐
- 【转】python数据格式化之pprint
pprint – 美观打印 作用:美观打印数据结构 pprint 包含一个“美观打印机”,用于生成数据结构的一个美观视图.格式化工具会生成数据结构的一些表示,不仅可以由解释器正确地解析,而且便于人类阅 ...
- 在X64系统中PowerDesigner无法连接MySQL的解决方法
在MySQL的官网http://dev.mysql.com/downloads/connector/odbc/下载,下个X64版本的,顺带也下了个X86的. 下载完成安装一切顺利(因为是X64系统,自 ...
- 使用spark对hive表中的多列数据判重
本文处理的场景如下,hive表中的数据,对其中的多列进行判重deduplicate. 1.先解决依赖,spark相关的所有包,pom.xml spark-hive是我们进行hive表spark处理的关 ...
- vDSP加速的应用
vDSP 是IOS提供一系列加速处理算法..在优化时可以考虑应用一二... 1.在项目中加入Accelerate.framework库 点开项目属性->Build Phases->Link ...
- VB6文件操作自定义函数合集之一
'--与文件及文件夹操作相关的函数 '--必须引用FSO的ACTIVE OBJECT Dim strList As String '--列表串,返回文件列表 '================ '-- ...
- ASP.NET Core 2.0 in Docker on Windows Container
安装Docker for Windows https://store.docker.com/editions/community/docker-ce-desktop-windows 要想将一个ASP. ...
- Python实现网站注册验证码生成类
# -*- coding:utf-8 -*- ''' Created on 2017年4月7日 @author: Water ''' import os import random import st ...
- 为什么C++没有对应realloc的new操作符呢?
http://blog.csdn.net/rabbit729/article/details/3400260 这个用memcpy明显是有问题的.如果类有资源分配的话,直接memcpy不能复制资源,会导 ...
- java语言插入数组中一个数,仍然能够实现排序
package com.llh.demo; import java.util.Scanner; /** * * @author llh * */ public class Demo16 { /* * ...
- lua State加载部分库
lua State加载部分库 在lua中,通常我们用luaL_openlibs(L)加载所有的lub标准库,但是有时候我们想只加载部分,有没有什么好的办法呢?在luaproc看到如下办法: stati ...