Netty是一个高性能 事件驱动的异步的非堵塞的IO(NIO)框架,用于建立TCP等底层的连接,基于Netty可以建立高性能的Http服务器。 1、首先来复习下非堵塞IO(NIO) NIO这个库是在JDK1.4中才引入的。NIO和IO有相同的作用和目的,但实现方式不同,NIO主要用到的是块,所以NIO的效率要比IO高很多。 在Java API中提供了两套NIO,一套是针对标准输入输出NIO,另一套就是网络编程NIO。 *Buffer和Channel是标准NIO中的核心对象* Channel是对原IO中流的模拟,任何来源和目的数据都必须通过一个Channel对象。一个Buffer实质上是一个容器对象,发给Channel的所有对象都必须先放到Buffer中;同样的,从Channel中读取的任何数据都要读到Buffer中。  网络编程NIO中还有一个核心对象Selector,它可以注册到很多个Channel上,监听各个Channel上发生的事件,并且能够根据事件情况决定Channel读写。这样,通过一个线程管理多个Channel,就可以处理大量网络连接了。  Selector 就是注册对各种 I/O 事件兴趣的地方,而且当那些事件发生时,就是这个对象告诉你所发生的事件。 Selector selector = Selector.open(); //创建一个selector 为了能让Channel和Selector配合使用,我们需要把Channel注册到Selector上。通过调用channel.register()方法来实现注册: channel.configureBlocking(false); //设置成异步IO SelectionKey key =channel.register(selector,SelectionKey.OP_READ); //对所关心的事件进行注册(connet,accept,read,write) SelectionKey 代表这个通道在此 Selector 上的这个注册。 2、异步 CallBack:回调是异步处理经常用到的编程模式,回调函数通常被绑定到一个方法上,并且在方法完成之后才执行,这种处理方式在javascript当中得到了充分的运用。回调给我们带来的难题是当一个问题处理过程中涉及很多回调时,代码是很难读的。 Futures:Futures是一种抽象,它代表一个事情的执行过程中的一些关键点,我们通过Future就可以知道任务的执行情况,比如当任务没完成时我们可以做一些其它事情。它给我们带来的难题是我们需要去判断future的值来确定任务的执行状态。 3、netty到底怎么工作的呢? 直接来看个最简单的实例 服务器端 - public class EchoServer {
-
- private final static int port = 8007;
-
- public void start() throws InterruptedException{
- ServerBootstrap bootstrap = new ServerBootstrap(); //引导辅助程序
- EventLoopGroup group = new NioEventLoopGroup(); //通过nio的方式接受连接和处理连接
- try {
- bootstrap.group(group)
- .channel(NioServerSocketChannel.class) //设置nio类型的channel
- .localAddress(new InetSocketAddress(port)) //设置监听端口
- .childHandler(new ChannelInitializer<SocketChannel>() { //有连接到达时会创建一个channel
- // pipline 管理channel中的handler,在channel队列中添加一个handler来处理业务
- @Override
- protected void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast("myHandler", new EchoServerHandler());
- //ch.pipeline().addLast("idleStateHandler",new IdleStateHandler(0, 0, 180));
-
- }
- });
- ChannelFuture future = bootstrap.bind().sync(); //配置完成,绑定server,并通过sync同步方法阻塞直到绑定成功
- System.out.println(EchoServer.class.getName() + " started and listen on " + future.channel().localAddress());
- future.channel().closeFuture().sync(); //应用程序会一直等待,直到channel关闭
- } catch (Exception e) {
- e.getMessage();
- }finally {
- group.shutdownGracefully().sync();
- }
- }
复制代码 创建一个ServerBootstrap实例 创建一个EventLoopGroup来处理各种事件,如处理链接请求,发送接收数据等。 定义本地InetSocketAddress( port)好让Server绑定 创建childHandler来处理每一个链接请求 所有准备好之后调用ServerBootstrap.bind()方法绑定Server handler 处理核心业务 - @Sharable //注解@Sharable可以让它在channels间共享
- public class EchoServerHandler extends ChannelInboundHandlerAdapter{
-
- @Override
- public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception {
- ByteBuf buf = ctx.alloc().buffer();
- buf.writeBytes("Hello World".getBytes());
- ctx.write(buf);
- }
-
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- ctx.flush();
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- cause.printStackTrace();
- ctx.close();
- }
- }
复制代码客户端 连接 - public class EchoClient {
- private final int port;
- private final String hostIp;
- public EchoClient(int port, String hostIp) {
- this.port = port;
- this.hostIp = hostIp;
- }
- public void start() throws InterruptedException {
- Bootstrap bootstrap = new Bootstrap();
- EventLoopGroup group = new NioEventLoopGroup();
- try {
- bootstrap.group(group).channel(NioSocketChannel.class)
- .remoteAddress(new InetSocketAddress(hostIp, port))
- .handler(new ChannelInitializer<SocketChannel>() {
- @Override
- protected void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast(new EchoClientHandler());
- }
- });
- ChannelFuture future = bootstrap.connect().sync();
- future.addListener(new ChannelFutureListener() {
- public void operationComplete(ChannelFuture future) throws Exception {
- if (future.isSuccess()) {
- System.out.println("client connected");
- } else {
- System.out.println("server attemp failed");
- future.cause().printStackTrace();
- }
- }
- });
- future.channel().closeFuture().sync();
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- group.shutdownGracefully().sync();
- }
- }
复制代码客户端handler - @Sharable
- public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
-
- /**
- *此方法会在连接到服务器后被调用
- * */
- public void channelActive(ChannelHandlerContext ctx) {
- System.out.println("Netty rocks!");
- ctx.write(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
- }
-
- /**
- * 接收到服务器数据时调用
- */
- @Override
- protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
- System.out.println("Client received: " + ByteBufUtil.hexDump(msg.readBytes(msg.readableBytes())));
- }
-
- /**
- *捕捉到异常
- * */
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- cause.printStackTrace();
- ctx.close();
- }
-
- }
复制代码 |