1. Channel组件
核心的针对BIO/NIO提供的抽象的网络通道,支持读,写,连接和绑定。
Channel
A nexus to a network socket or a component which is capable of I/O operations such as read, write, connect, and bind.
ChannelFactoryCreates a Channel associated with a certain communication entity such as a network socket.
2. ChannelPipeline组件
可以理解为ChannelHandler的容器,主要负责通道的可读,可写,连接和绑定等事件在管道化的一系列ChannelHandler中的流转。所有ChannelHandler都必须注册到ChannelPipeline中按顺序组织起来。
ChannelPipeline
A list of ChannelHandlers which handles or interceptsChannelEvents of aChannel.
ChannelPipelineFactory
Creates a new ChannelPipeline for a newChannel.
3. ChannelHandler组件
提供针对通道的可读,可写,连接和绑定等事件的处理接口,主要负责实际与网络IO无关的业务逻辑的处理。
ChannelHandler
Handles or intercepts a ChannelEvent, and sends aChannelEvent to the next handler in aChannelPipeline.
ChannelHandlerContext
Enables a ChannelHandler to interact with itsChannelPipeline and other handlers.
4. ChannelFuture组件
针对通道的读,写,连接和绑定等异步IO操作的抽象,类似于JDK中提供的Future。一个ChannelFuture对象代表了一个尚未发生的I/O操作。这意味着,任何已请求的操作都可能是没有被立即执行的,因为在Netty内部所有的操作都是异步的。
ChannelFuture
The result of an asynchronous Channel I/O operation.
ChannelFutureListener
Listens to the result of a ChannelFuture.
5. ChannelBuffer组件
Netty中的buffer是完全重新实现的,与NIO ByteBuffer完全不同。如果要说NIO的Buffer和Netty的ChannelBuffer最大的区别的话,就是前者仅仅是传输上的Buffer,而后者其实是传输Buffer和抽象后的逻辑Buffer的结合。
ChannelBufferA random and sequential accessible sequence of zero or more bytes (octets). This interface provides an abstract view for one or more primitive byte arrays (byte[]) andNIO buffers.
6. ChannelEvent组件
ChannelEvent是数据或者状态的载体,当对Channel进行操作时,会产生一个ChannelEvent,并发送到ChannelPipeline。
ChannelEvent
An I/O event or I/O request associated with a Channel.
A ChannelEvent is handled by a series of ChannelHandlers in a ChannelPipeline.
Netty是什么?
本质:JBoss做的一个Jar包
目的:快速开发高性能、高可靠性的网络服务器和客户端程序
优点:提供异步的、事件驱动的网络应用程序框架和工具
通俗的说:一个好使的处理Socket的东东
Netty的特性
设计
统一的API,适用于不同的协议(阻塞和非阻塞)
基于灵活、可扩展的事件驱动模型
高度可定制的线程模型
可靠的无连接数据Socket支持(UDP)
性能
更好的吞吐量,低延迟
更省资源
尽量减少不必要的内存拷贝
安全
完整的SSL/TLS和STARTTLS的支持
能在Applet与Android的限制环境运行良好
健壮性
不再因过快、过慢或超负载连接导致OutOfMemoryError
不再有在高速网络环境下NIO读写频率不一致的问题
易用
完善的JavaDoc,用户指南和样例
简洁简单
下面提供一个简单的例子
第一步:下载netty5.0
移步官网下载 http://netty.io/downloads.html或者
使用maven,在pom.xml中添加如下代码
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>5.0.0.Alpha2</version> </dependency>第二步: 编写Server端代码
NettyServerBootstrap代码
import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.timeout.IdleStateHandler; public class NettyServerBootstrap { private static Logger logger = Logger.getLogger(NettyServerBootstrap.class); private int port; public NettyServerBootstrap(int port) { this.port = port; bind(); } private void bind() { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker); bootstrap.channel(NioServerSocketChannel.class); bootstrap.option(ChannelOption.SO_BACKLOG, 1024); //连接数 bootstrap.option(ChannelOption.TCP_NODELAY, true); //不延迟,消息立即发送 bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); //长连接 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline p = socketChannel.pipeline(); p.addLast(new NettyServerHandler()); } }); ChannelFuture f = bootstrap.bind(port).sync(); if (f.isSuccess()) { logger.debug("启动Netty服务成功,端口号:" + this.port); } // 关闭连接 f.channel().closeFuture().sync(); } catch (Exception e) { logger.error("启动Netty服务异常,异常信息:" + e.getMessage()); e.printStackTrace(); } finally { boss.shutdownGracefully(); worker.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { NettyServerBootstrap server= new NettyServerBootstrap(9999); } }NettyServerHandler代码
import java.io.UnsupportedEncodingException; import com.datong.base.module.netty.common.Constant; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; public class NettyServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; String recieved = getMessage(buf); System.out.println("服务器接收到消息:" + recieved); try { ctx.writeAndFlush(getSendByteBuf("APPLE")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /* * 从ByteBuf中获取信息 使用UTF-8编码返回 */ private String getMessage(ByteBuf buf) { byte[] con = new byte[buf.readableBytes()]; buf.readBytes(con); try { return new String(con, Constant.UTF8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } private ByteBuf getSendByteBuf(String message) throws UnsupportedEncodingException { byte[] req = message.getBytes("UTF-8"); ByteBuf pingMessage = Unpooled.buffer(); pingMessage.writeBytes(req); return pingMessage; } }第三步:编写Client代码
NettyClient代码
import java.util.concurrent.TimeUnit; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.timeout.IdleStateHandler; public class NettyClient { /* * 服务器端口号 */ private int port; /* * 服务器IP */ private String host; public NettyClientBootstrap(int port, String host) throws InterruptedException { this.port = port; this.host = host; start(); } private void start() throws InterruptedException { EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.group(eventLoopGroup); bootstrap.remoteAddress(host, port); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new NettyClientHandler()); } }); ChannelFuture future = bootstrap.connect(host, port).sync(); if (future.isSuccess()) { socketChannel = (SocketChannel) future.channel(); System.out.println("----------------connect server success----------------"); } future.channel().closeFuture().sync(); } finally { eventLoopGroup.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { NettyClient client = new NettyClient(9999, "localhost"); } }NettyClientHandler代码
import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; import com.netty.common.NettyStartRunable; import com.netty.common.ProxyPool; import com.netty.util.JsonUtil; import net.sf.json.JSONObject; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; public class NettyClientHandler extends ChannelHandlerAdapter { private ByteBuf firstMessage; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { byte[] data = "服务器,给我一个APPLE".getBytes(); firstMessage=Unpooled.buffer(); firstMessage.writeBytes(data); ctx.writeAndFlush(firstMessage); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; String rev = getMessage(bug); System.out.println("客户端收到服务器数据:" + rev); } private String getMessage(ByteBuf buf) { byte[] con = new byte[buf.readableBytes()]; buf.readBytes(con); try { return new String(con, Constant.UTF8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } }