java 自己动手实现一个分布式系统 之 Netty篇 handler()和childHandler()

handler()和childHandler()的主要区别是,handler()是发生在初始化的时候,childHandler()是发生在客户端连接之后

也就是说,如果需要在客户端连接前的请求进行handler处理,则需要配置handler(),如果是处理客户端连接之后的handler,则需要配置在childHandler()。

下面是看看源码中是怎么实现的。
ServerBootstrap#init()

@Override
void init(Channel channel) throws Exception {
    // 所有的选项
    final Map<ChannelOption<?>, Object> options = options0();
    synchronized (options) {
        setChannelOptions(channel, options, logger);
    }

    // 所有的属性
    final Map<AttributeKey<?>, Object> attrs = attrs0();
    synchronized (attrs) {
        for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
            @SuppressWarnings("unchecked")
            AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
            channel.attr(key).set(e.getValue());
        }
    }

    // 管道,在创建Channel的时候会默认创建一个
    ChannelPipeline p = channel.pipeline();

    final EventLoopGroup currentChildGroup = childGroup;
    final ChannelHandler currentChildHandler = childHandler;
    final Entry<ChannelOption<?>, Object>[] currentChildOptions;
    final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
    synchronized (childOptions) {
        currentChildOptions = childOptions.entrySet().toArray(newOptionArray(0));
    }
    synchronized (childAttrs) {
        currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(0));
    }

    // 添加管道处理
    p.addLast(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(final Channel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            // 处理器
            ChannelHandler handler = config.handler();
            // 处理客户端连接之前会把handler添加到pipeline中
            if (handler != null) {
                pipeline.addLast(handler);
            }

            // 增加一个ServerBootstrapAcceptor
            // 这里用来处理新的客户端连接
            ch.eventLoop().execute(new Runnable() {
                @Override
                public void run() {
                    pipeline.addLast(new ServerBootstrapAcceptor(
                            ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                }
            });
        }
    });
}

ServerBootstrapAcceptor的channelRead()

@Override
@SuppressWarnings("unchecked")
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    final Channel child = (Channel) msg;

    // 这里会把childHandler的handler处理器也添加到pipeline
    child.pipeline().addLast(childHandler);

    setChannelOptions(child, childOptions, logger);

    for (Entry<AttributeKey<?>, Object> e: childAttrs) {
        child.attr((AttributeKey<Object>) e.getKey()).set(e.getValue());
    }

    try {
        // 注册新的连接
        // 建立连接后,把消息处理就交给workerBoss线程池去处理了
        childGroup.register(child).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    forceClose(child, future.cause());
                }
            }
        });
    } catch (Throwable t) {
        forceClose(child, t);
    }
}

所以说,childHandler()配置的handler是客户端连接之后才会处理的。

其实,option和childOption也是一样的道理。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
实现一个Netty一样的功能Server端和client端,可以使用Java NIO来进行实现。下面是一个简单的示例代码: ### Server端 ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class NioServer { private Selector selector; private ByteBuffer readBuffer = ByteBuffer.allocate(1024); private ByteBuffer writeBuffer = ByteBuffer.allocate(1024); public NioServer(int port) { try { // 创建ServerSocketChannel对象并绑定端口 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(port)); serverSocketChannel.configureBlocking(false); // 创建Selector对象 selector = Selector.open(); // 将ServerSocketChannel注册到Selector上,并设置为监听OP_ACCEPT事件 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Server started, listening on port " + port); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void start() { try { while (true) { // 阻塞等待事件的发生 selector.select(); // 获取发生事件的SelectionKey集合 Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); iterator.remove(); if (selectionKey.isAcceptable()) { // ServerSocketChannel可以接收客户端连接 ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ); System.out.println("Client " + socketChannel.getRemoteAddress() + " connected."); } else if (selectionKey.isReadable()) { // SocketChannel可以读取数据 SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); readBuffer.clear(); int numRead = socketChannel.read(readBuffer); if (numRead == -1) { // 客户端关闭连接 selectionKey.cancel(); socketChannel.close(); System.out.println("Client " + socketChannel.getRemoteAddress() + " disconnected."); } else { // 处理读取到的数据 String request = new String(readBuffer.array(), 0, numRead); System.out.println("Received request from client " + socketChannel.getRemoteAddress() + ": " + request); socketChannel.register(selector, SelectionKey.OP_WRITE); } } else if (selectionKey.isWritable()) { // SocketChannel可以写入数据 SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); writeBuffer.clear(); String response = "Hello from server!"; writeBuffer.put(response.getBytes()); writeBuffer.flip(); socketChannel.write(writeBuffer); socketChannel.register(selector, SelectionKey.OP_READ); } } } } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { NioServer server = new NioServer(8888); server.start(); } } ``` ### Client端 ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class NioClient { private Selector selector; private ByteBuffer readBuffer = ByteBuffer.allocate(1024); private ByteBuffer writeBuffer = ByteBuffer.allocate(1024); public NioClient(String host, int port) { try { // 创建SocketChannel对象并连接服务器 SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress(host, port)); // 创建Selector对象 selector = Selector.open(); // 将SocketChannel注册到Selector上,并设置为监听OP_CONNECT事件 socketChannel.register(selector, SelectionKey.OP_CONNECT); System.out.println("Connecting to server " + host + ":" + port); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void start() { try { while (true) { // 阻塞等待事件的发生 selector.select(); // 获取发生事件的SelectionKey集合 Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); iterator.remove(); if (selectionKey.isConnectable()) { // SocketChannel已连接到服务器 SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); if (socketChannel.isConnectionPending()) { socketChannel.finishConnect(); } socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_WRITE); System.out.println("Connected to server " + socketChannel.getRemoteAddress()); } else if (selectionKey.isReadable()) { // SocketChannel可以读取数据 SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); readBuffer.clear(); int numRead = socketChannel.read(readBuffer); if (numRead == -1) { // 服务器关闭连接 selectionKey.cancel(); socketChannel.close(); System.out.println("Server " + socketChannel.getRemoteAddress() + " disconnected."); } else { // 处理读取到的数据 String response = new String(readBuffer.array(), 0, numRead); System.out.println("Received response from server " + socketChannel.getRemoteAddress() + ": " + response); socketChannel.register(selector, SelectionKey.OP_WRITE); } } else if (selectionKey.isWritable()) { // SocketChannel可以写入数据 SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); writeBuffer.clear(); String request = "Hello from client!"; writeBuffer.put(request.getBytes()); writeBuffer.flip(); socketChannel.write(writeBuffer); socketChannel.register(selector, SelectionKey.OP_READ); } } } } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { NioClient client = new NioClient("localhost", 8888); client.start(); } } ``` 这个示例代码实现一个简单的NIO Server和Client,可以接收客户端连接,读取客户端发送的数据,并回复一条消息。虽然它没有Netty那么强大,但是可以作为一个参考来了解Java NIO的基本原理和使用方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值