`

Netty4.0学习笔记系列之二:Handler的执行顺序

阅读更多

        Handler在netty中,无疑占据着非常重要的地位。Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码、拦截指定的报文、统一对日志错误进行处理、统一对请求进行计数、控制Handler执行与否。一句话,没有它做不到的只有你想不到的。

        Netty中的所有handler都实现自ChannelHandler接口。按照输出输出来分,分为ChannelInboundHandler、ChannelOutboundHandler两大类。ChannelInboundHandler对从客户端发往服务器的报文进行处理,一般用来执行解码、读取客户端数据、进行业务处理等;ChannelOutboundHandler对从服务器发往客户端的报文进行处理,一般用来进行编码、发送报文到客户端。

        Netty中,可以注册多个handler。ChannelInboundHandler按照注册的先后顺序执行;ChannelOutboundHandler按照注册的先后顺序逆序执行,如下图所示,按照注册的先后顺序对Handler进行排序,request进入Netty后的执行顺序为:


        基本的概念就说到这,下面用一个例子来进行验证。该例子模拟Client与Server间的通讯,Server端注册了2个ChannelInboundHandler、2个ChannelOutboundHandler。当Client连接到Server后,会向Server发送一条消息。Server端通过ChannelInboundHandler 对Client发送的消息进行读取,通过ChannelOutboundHandler向client发送消息。最后Client把接收到的信息打印出来。

        Server端一共有5个类:HelloServer.java、InboundHandler1.java、InboundHandler2.java、OutboundHandler1.java、OutboundHandler2.java

1.HelloServer.java

package com.bijian.netty.server;

import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;

public class HelloServer {
    
    public void start(int port) throws Exception {
        
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            // 注册两个OutboundHandler,执行顺序为注册顺序的逆序,所以应该是OutboundHandler2 OutboundHandler1
                            ch.pipeline().addLast(new OutboundHandler1());
                            ch.pipeline().addLast(new OutboundHandler2());
                            // 注册两个InboundHandler,执行顺序为注册顺序,所以应该是InboundHandler1 InboundHandler2
                            ch.pipeline().addLast(new InboundHandler1());
                            ch.pipeline().addLast(new InboundHandler2());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();

            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        HelloServer server = new HelloServer();
        server.start(8000);
    }
}

2.InboundHandler1.java

package com.bijian.netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InboundHandler1 extends ChannelInboundHandlerAdapter {
    
    private static Logger logger = LoggerFactory.getLogger(InboundHandler1.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("InboundHandler1.channelRead: ctx :" + ctx);
        // 通知执行下一个InboundHandler
        ctx.fireChannelRead(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        logger.info("InboundHandler1.channelReadComplete");
        ctx.flush();
    }
}

3.InboundHandler2.java

package com.bijian.netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InboundHandler2 extends ChannelInboundHandlerAdapter {
    
    private static Logger logger = LoggerFactory.getLogger(InboundHandler2.class);

    @Override
    // 读取Client发送的信息,并打印出来
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("InboundHandler2.channelRead: ctx :" + ctx);
        ByteBuf result = (ByteBuf) msg;
        byte[] result1 = new byte[result.readableBytes()];
        result.readBytes(result1);
        String resultStr = new String(result1);
        System.out.println("Client said:" + resultStr);
        result.release();

        ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        logger.info("InboundHandler2.channelReadComplete");
        ctx.flush();
    }
}

4.OutboundHandler1.java

package com.bijian.netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OutboundHandler1 extends ChannelOutboundHandlerAdapter {
    
    private static Logger logger = LoggerFactory.getLogger(OutboundHandler1.class);

    @Override
    // 向client发送消息
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        logger.info("OutboundHandler1.write");
        String response = "I am ok!";
        ByteBuf encoded = ctx.alloc().buffer(4 * response.length());
        encoded.writeBytes(response.getBytes());
        ctx.write(encoded);
        ctx.flush();
    }
}

5.OutboundHandler2.java

package com.bijian.netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OutboundHandler2 extends ChannelOutboundHandlerAdapter {
    
    private static Logger logger = LoggerFactory.getLogger(OutboundHandler2.class);

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        logger.info("OutboundHandler2.write");
        // 执行下一个OutboundHandler
        super.write(ctx, msg, promise);
    }
}

Client端有两个类:HelloClient.java、HelloClientIntHandler.java

1.HelloClient.java  

package com.bijian.netty.client;

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;

public class HelloClient {
    
    public void connect(String host, int port) throws Exception {

        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new HelloClientIntHandler());
                }
            });

            // Start the client.  
            ChannelFuture f = b.connect(host, port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        HelloClient client = new HelloClient();
        client.connect("127.0.0.1", 8000);
    }
}

2.HelloClientIntHandler.java

package com.bijian.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloClientIntHandler extends ChannelInboundHandlerAdapter {
    
    private static Logger logger = LoggerFactory.getLogger(HelloClientIntHandler.class);

    @Override
    // 读取服务端的信息
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("HelloClientIntHandler.channelRead");
        ByteBuf result = (ByteBuf) msg;
        byte[] result1 = new byte[result.readableBytes()];
        result.readBytes(result1);
        result.release();
        ctx.close();
        System.out.println("Server said:" + new String(result1));
    }

    @Override
    // 当连接建立的时候向服务端发送消息 ,channelActive 事件当连接建立的时候会触发
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("HelloClientIntHandler.channelActive");
        String msg = "Are you ok?";
        ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());
        encoded.writeBytes(msg.getBytes());
        ctx.write(encoded);
        ctx.flush();
    }
}

        server端执行结果为:


        在使用Handler的过程中,需要注意:

        1.ChannelInboundHandler之间的传递,通过调用 ctx.fireChannelRead(msg) 实现;调用ctx.write(msg) 将传递到ChannelOutboundHandler。

        2.ctx.write()方法执行后,需要调用flush()方法才能令它立即执行。

        3.ChannelOutboundHandler 在注册的时候需要放在最后一个ChannelInboundHandler之前,否则将无法传递到ChannelOutboundHandler。

 

文章来源:http://blog.csdn.net/u013252773/article/details/21195593

  • 大小: 32.7 KB
  • 大小: 26.8 KB
分享到:
评论

相关推荐

    Netty4.0学习笔记系列之四:混合使用coder和handler

    在本篇Netty4.0学习笔记中,我们将聚焦于如何在实际应用中混合使用`coder`和`handler`,这是Netty框架中非常关键的一部分,对于构建高性能、低延迟的网络应用程序至关重要。Netty是一个用Java编写的异步事件驱动的...

    Netty4.0学习笔记系列之五:自定义通讯协议

    在本篇“Netty4.0学习笔记系列之五:自定义通讯协议”中,我们将深入探讨如何在Netty框架下构建和实现自己的通信协议。Netty是一个高性能、异步事件驱动的网络应用框架,广泛应用于Java领域的服务器开发,如网络游戏...

    Netty4.0学习笔记系列之六:多种通讯协议支持

    在本篇Netty4.0学习笔记系列之六中,我们将深入探讨Netty框架如何支持多种通讯协议,以及它在实现高效、灵活的网络通信中的关键特性。Netty是一个高性能、异步事件驱动的网络应用框架,适用于开发服务器和客户端的...

    Netty4.0学习笔记系列之三:构建简单的http服务

    Netty4.0学习笔记系列之三是关于构建简单的HTTP服务的教程,这主要涉及网络编程、服务器开发以及Java NIO(非阻塞I/O)的相关知识。Netty是一个高性能、异步事件驱动的网络应用程序框架,它使得开发可伸缩且稳定的...

    Netty4.0学习笔记系列之一:Server与Client的通讯

    在本文中,我们将深入探讨Netty 4.0的学习笔记,特别是关于Server与Client之间的通信机制。 首先,我们要理解Netty的核心概念——NIO(非阻塞I/O)。Netty基于Java NIO库构建,它提供了更高级别的API,简化了多路...

    Netty4.0 jar包 及 源代码 和 例子

    Netty4.0全部jar包.开发时候只需要倒入总的哪一个netty4.0.jar就行了 后缀为resources.jar的全部是源码。 简单的代码例子在netty-example-resources.jar里面。

    netty4.0文件分片上传+断点续传+权限校验

    Netty 是一个高性能、异步事件驱动...rrkd-file-client和rrkd-file-server这两个文件可能包含了实现上述功能的客户端和服务端代码示例,通过分析和学习这些代码,开发者可以更好地理解和应用Netty进行文件上传的实践。

    Netty4.0 官网例子(免费)

    Netty4.0 是其一个重要版本,引入了诸多改进和新特性。 在 Netty4.0 中,主要知识点包括: 1. **ByteBuf**:Netty4.0 引入了 ByteBuf 作为缓冲区,替代了传统的 ByteBuffer。ByteBuf 提供了更高效的内存管理,支持...

    netty4.0工具包

    NIO socket开发,netty4.0工具包。

    Netty4.0 http案例

    在这个“Netty4.0 http案例”中,我们将深入探讨如何利用Netty 4.0 实现HTTP服务,以及客户端如何通过HTTP请求与服务器进行交互,特别是在处理JSON格式的数据时。 首先,让我们了解HTTP协议。HTTP(超文本传输协议...

    Springboot 2.0 整合 Netty 4.0 实现IO异步通讯架构

    Springboot2.0.8集成 netty4 ,使用protobuf作为ping的数据交换,比json更加的小巧,占用数据量更小,可用于任何第三方应用做心跳监控。 已完成功能: - 客户端授权验证(基于protoBuff) - 心跳检测(基于protoBuff) ...

    netty4.0源码,netty例子,netty api文档

    这个压缩包包含的是Netty 4.0.0.CR3版本的相关资源,包括源码、示例以及API文档,对于学习和理解Netty的工作原理以及如何在实际项目中应用Netty非常有帮助。 首先,让我们来详细探讨一下Netty的核心特性: 1. **...

    netty-all-4.0.50.Final-API文档-中文版.zip

    赠送jar包:netty-all-4.0.50.Final.jar; 赠送原API文档:netty-all-4.0.50.Final-javadoc.jar; 赠送源代码:netty-all-4.0.50.Final-sources.jar; 赠送Maven依赖信息文件:netty-all-4.0.50.Final.pom; 包含...

    netty4.0 demo

    这个"Netty4.0 demo"压缩包包含了一些Netty 4.0版本的应用示例代码,可以帮助我们更好地理解和学习Netty的工作原理以及如何在实际项目中运用它。 1. **Netty简介** Netty 是由JBOSS组织开发的一个开源项目,最初...

    netty4.0.45jar包socket和http工具包

    Netty 是一个高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端。在本文中,我们将深入探讨Netty 4.0.45版本在Socket和HTTP开发中的应用,以及它如何在实际的保险项目中提供...

    netty4.0中的新变化和注意点鸟窝.pdf

    在 Netty 4.0 中,引入了一系列重大改进和变化,旨在提高性能、可维护性和易用性。以下是这些变化的详细说明: 1. **工程结构的改变**: - 包名从 org.jboss.netty 更改为 io.netty,反映了项目的独立性。 - ...

    Netty4.0.54英文版API文档

    Netty4.0.54英文版API文档,与官网中文档内容一致,方便用户在离线环境下,开发Netty

    netty-resolver-dns-4.1.65.Final-API文档-中英对照版.zip

    赠送jar包:netty-resolver-dns-4.1.65.Final.jar; 赠送原API文档:netty-resolver-dns-4.1.65.Final-javadoc.jar; 赠送源代码:netty-resolver-dns-4.1.65.Final-sources.jar; 赠送Maven依赖信息文件:netty-...

    netty-4.0.28.Final

    Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序dsf。...netty, 4.0.28, Final, jar包, 含源码

Global site tag (gtag.js) - Google Analytics