All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zhuang.netty.NettyBase Maven / Gradle / Ivy

package com.zhuang.netty;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

abstract public class NettyBase {

    protected int port;
    protected List channelHandlerObjectList = new ArrayList<>();
    protected boolean sync = false;

    abstract public void start();

    abstract public void shutdown();

    protected ChannelInitializer createChannelInitializer() {
        return new ChannelInitializer() {
            @Override
            public void initChannel(SocketChannel socketChannel) {
                channelHandlerObjectList.forEach(c -> {
                    if (c instanceof ChannelHandler) {
                        socketChannel.pipeline().addLast((ChannelHandler) c);
                    } else if (c instanceof Supplier) {
                        socketChannel.pipeline().addLast(((Supplier) c).get());
                    }
                });
            }
        };
    }

    protected void setChannelFutureSync(ChannelFuture channelFuture) {
        if (sync) {
            try {
                channelFuture.sync();
                channelFuture.channel().closeFuture().sync();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 添加ChannelHandler的Supplier
     *
     * @param handlerSupplier
     * @return
     */
    public NettyBase addChannelHandler(Supplier handlerSupplier) {
        channelHandlerObjectList.add(handlerSupplier);
        return this;
    }

    /**
     * 添加ChannelHandler(注意:该handler须加@ChannelHandler.Sharable注解)
     *
     * @param handler
     * @return
     */
    public NettyBase addChannelHandler(ChannelHandler handler) {
        channelHandlerObjectList.add(handler);
        return this;
    }

    public NettyBase setSync(boolean sync) {
        this.sync = sync;
        return this;
    }
}