Example usage for io.netty.channel ChannelInitializer ChannelInitializer

List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer

Introduction

In this page you can find the example usage for io.netty.channel ChannelInitializer ChannelInitializer.

Prototype

ChannelInitializer

Source Link

Usage

From source file:com.codnos.dbgp.internal.impl.DBGpIdeImpl.java

License:Apache License

@Override
public void startListening() {
    registerInitHandler();//from  ww w  .j a  va 2s .c  o  m
    ServerBootstrap b = new ServerBootstrap();
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(outboundConnectionHandler, new DBGpCommandEncoder(),
                            new DBGpResponseDecoder(), new DBGpResponseHandler(eventsHandler));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true);
    bindPort(b);
}

From source file:com.common.server.ScheduleServer.java

License:Apache License

public void startServer() throws Exception {
    try {/* ww w . ja v a 2s . c o  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new ScheduleServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(this.port).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.comphenix.protocol.compat.netty.independent.NettyProtocolInjector.java

License:Open Source License

/**
 * Inject into the spigot connection class.
 */// www.j  a va 2 s . c  om
@Override
@SuppressWarnings("unchecked")
public synchronized void inject() {
    if (injected)
        throw new IllegalStateException("Cannot inject twice.");
    try {
        FuzzyReflection fuzzyServer = FuzzyReflection.fromClass(MinecraftReflection.getMinecraftServerClass());
        List<Method> serverConnectionMethods = fuzzyServer
                .getMethodListByParameters(MinecraftReflection.getServerConnectionClass(), new Class[] {});

        // Get the server connection
        Object server = fuzzyServer.getSingleton();
        Object serverConnection = null;

        for (Method method : serverConnectionMethods) {
            try {
                serverConnection = method.invoke(server);

                // Continue until we get a server connection
                if (serverConnection != null) {
                    break;
                }
            } catch (Exception e) {
                // Try the next though
                e.printStackTrace();
            }
        }

        // Handle connected channels
        final ChannelInboundHandler endInitProtocol = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                try {
                    // This can take a while, so we need to stop the main thread from interfering
                    synchronized (networkManagers) {
                        injectionFactory.fromChannel(channel, NettyProtocolInjector.this, playerFactory)
                                .inject();
                    }
                } catch (Exception e) {
                    reporter.reportDetailed(NettyProtocolInjector.this, Report
                            .newBuilder(REPORT_CANNOT_INJECT_INCOMING_CHANNEL).messageParam(channel).error(e));
                }
            }
        };

        // This is executed before Minecraft's channel handler
        final ChannelInboundHandler beginInitProtocol = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                // Our only job is to add init protocol
                channel.pipeline().addLast(endInitProtocol);
            }
        };

        // Add our handler to newly created channels
        final ChannelHandler connectionHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                Channel channel = (Channel) msg;

                // Prepare to initialize ths channel
                channel.pipeline().addFirst(beginInitProtocol);
                ctx.fireChannelRead(msg);
            }
        };

        // Get the current NetworkMananger list
        networkManagers = (List<Object>) FuzzyReflection.fromObject(serverConnection, true).invokeMethod(null,
                "getNetworkManagers", List.class, serverConnection);

        // Insert ProtocolLib's connection interceptor
        bootstrapFields = getBootstrapFields(serverConnection);

        for (VolatileField field : bootstrapFields) {
            final List<Object> list = (List<Object>) field.getValue();

            // We don't have to override this list
            if (list == networkManagers) {
                continue;
            }

            // Synchronize with each list before we attempt to replace them.
            field.setValue(new NettyBootstrapList(list, connectionHandler));
        }

        injected = true;

    } catch (Exception e) {
        throw new RuntimeException("Unable to inject channel futures.", e);
    }
}

From source file:com.comphenix.protocol.injector.netty.ProtocolInjector.java

License:Open Source License

/**
 * Inject into the spigot connection class.
 *//* w ww.j av  a2 s  .c  o m*/
@SuppressWarnings("unchecked")
public synchronized void inject() {
    if (injected)
        throw new IllegalStateException("Cannot inject twice.");
    try {
        FuzzyReflection fuzzyServer = FuzzyReflection.fromClass(MinecraftReflection.getMinecraftServerClass());
        List<Method> serverConnectionMethods = fuzzyServer
                .getMethodListByParameters(MinecraftReflection.getServerConnectionClass(), new Class[] {});

        // Get the server connection
        Object server = fuzzyServer.getSingleton();
        Object serverConnection = null;

        for (Method method : serverConnectionMethods) {
            try {
                serverConnection = method.invoke(server);

                // Continue until we get a server connection
                if (serverConnection != null) {
                    break;
                }
            } catch (Exception e) {
                // Try the next though
                e.printStackTrace();
            }
        }

        // Handle connected channels
        final ChannelInboundHandler endInitProtocol = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(final Channel channel) throws Exception {
                try {
                    synchronized (networkManagers) {
                        // For some reason it needs to be delayed on 1.12, but the delay breaks 1.11 and below
                        // TODO I see this more as a temporary hotfix than a permanent solution
                        if (MinecraftVersion.getCurrentVersion().getMinor() >= 12) {
                            channel.eventLoop().submit(() -> injectionFactory
                                    .fromChannel(channel, ProtocolInjector.this, playerFactory).inject());
                        } else {
                            injectionFactory.fromChannel(channel, ProtocolInjector.this, playerFactory)
                                    .inject();
                        }
                    }
                } catch (Exception e) {
                    reporter.reportDetailed(ProtocolInjector.this, Report
                            .newBuilder(REPORT_CANNOT_INJECT_INCOMING_CHANNEL).messageParam(channel).error(e));
                }
            }
        };

        // This is executed before Minecraft's channel handler
        final ChannelInboundHandler beginInitProtocol = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                // Our only job is to add init protocol
                channel.pipeline().addLast(endInitProtocol);
            }
        };

        // Add our handler to newly created channels
        final ChannelHandler connectionHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                Channel channel = (Channel) msg;

                // Prepare to initialize ths channel
                channel.pipeline().addFirst(beginInitProtocol);
                ctx.fireChannelRead(msg);
            }
        };

        FuzzyReflection fuzzy = FuzzyReflection.fromObject(serverConnection, true);

        try {
            List<Field> fields = fuzzy.getFieldListByType(List.class);
            for (Field field : fields) {
                ParameterizedType param = (ParameterizedType) field.getGenericType();
                if (param.getActualTypeArguments()[0].equals(MinecraftReflection.getNetworkManagerClass())) {
                    field.setAccessible(true);
                    networkManagers = (List<Object>) field.get(serverConnection);
                }
            }
        } catch (Exception ex) {
            networkManagers = (List<Object>) fuzzy
                    .getMethodByParameters("getNetworkManagers", List.class, serverConnection.getClass())
                    .invoke(null, serverConnection);
        }

        if (networkManagers == null) {
            throw new RuntimeException("Failed to obtain list of network managers.");
        }

        // Insert ProtocolLib's connection interceptor
        bootstrapFields = getBootstrapFields(serverConnection);

        for (VolatileField field : bootstrapFields) {
            final List<Object> list = (List<Object>) field.getValue();

            // We don't have to override this list
            if (list == networkManagers) {
                continue;
            }

            // Synchronize with each list before we attempt to replace them.
            field.setValue(new BootstrapList(list, connectionHandler));
        }

        injected = true;
    } catch (Exception e) {
        throw new RuntimeException("Unable to inject channel futures.", e);
    }
}

From source file:com.couchbase.client.core.endpoint.AbstractEndpoint.java

License:Apache License

/**
 * Create a new {@link AbstractEndpoint}.
 *
 * @param hostname the hostname/ipaddr of the remote channel.
 * @param bucket the name of the bucket.
 * @param password the password of the bucket.
 * @param port the port of the remote channel.
 * @param environment the environment of the core.
 * @param responseBuffer the response buffer for passing responses up the stack.
 *//*from  w w w . j  a v  a 2s .c o m*/
protected AbstractEndpoint(final String hostname, final String bucket, final String password, final int port,
        final CoreEnvironment environment, final RingBuffer<ResponseEvent> responseBuffer,
        boolean isTransient) {
    super(LifecycleState.DISCONNECTED);
    this.bucket = bucket;
    this.password = password;
    this.responseBuffer = responseBuffer;
    this.env = environment;
    this.isTransient = isTransient;
    if (environment.sslEnabled()) {
        this.sslEngineFactory = new SSLEngineFactory(environment);
    }

    Class<? extends Channel> channelClass = NioSocketChannel.class;
    if (environment.ioPool() instanceof EpollEventLoopGroup) {
        channelClass = EpollSocketChannel.class;
    } else if (environment.ioPool() instanceof OioEventLoopGroup) {
        channelClass = OioSocketChannel.class;
    }

    ByteBufAllocator allocator = env.bufferPoolingEnabled() ? PooledByteBufAllocator.DEFAULT
            : UnpooledByteBufAllocator.DEFAULT;

    boolean tcpNodelay = environment().tcpNodelayEnabled();
    bootstrap = new BootstrapAdapter(
            new Bootstrap().remoteAddress(hostname, port).group(environment.ioPool()).channel(channelClass)
                    .option(ChannelOption.ALLOCATOR, allocator).option(ChannelOption.TCP_NODELAY, tcpNodelay)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, env.socketConnectTimeout())
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            if (environment.sslEnabled()) {
                                pipeline.addLast(new SslHandler(sslEngineFactory.get()));
                            }
                            if (LOGGER.isTraceEnabled()) {
                                pipeline.addLast(LOGGING_HANDLER_INSTANCE);
                            }
                            customEndpointHandlers(pipeline);
                        }
                    }));
}

From source file:com.couchbase.client.core.io.endpoint.AbstractEndpoint.java

License:Open Source License

/**
 * Create a new {@link AbstractEndpoint} and supply essential params.
 *
 * @param addr the socket address to connect to.
 * @param env the environment to attach to.
 * @param group the {@link EventLoopGroup} to use.
 *//*from ww  w  . j a  v  a2s  . c  o m*/
protected AbstractEndpoint(final InetSocketAddress addr, final Environment env, final EventLoopGroup group) {
    this.env = env;
    endpointStateDeferred = Streams.defer(env, defaultPromiseEnv);
    endpointStateStream = endpointStateDeferred.compose();

    connectionBootstrap = new BootstrapAdapter(new Bootstrap().group(group).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(final SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (LOGGER.isTraceEnabled()) {
                        pipeline.addLast(new LoggingHandler(LogLevel.TRACE));
                    }

                    customEndpointHandlers(pipeline);
                    pipeline.addLast(new GenericEndpointHandler<REQ, RES>());
                }
            }).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY, false).option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1500)
            .remoteAddress(addr));
}

From source file:com.ctrip.xpipe.redis.console.health.netty.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {//ww w  .j  a v  a2 s.com
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        }
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT);
        Channel c = f.channel();

        while (true) {
            ByteBuf buf = Unpooled.buffer(8);
            buf.writeLong(System.nanoTime());
            c.writeAndFlush(buf);
            Thread.sleep(1000);
        }

    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.ctrip.xpipe.redis.console.health.netty.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/* w  ww  . j a  v a  2 s . co m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption.TCP_NODELAY, true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.demo.netty.echo.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from w  w  w . j ava 2  s .  co  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    //EventLoopGroup is  abstraction of Notification and Thread loop
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup) //
                .channel(NioServerSocketChannel.class) //
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.digitalpetri.modbus.master.ModbusTcpMaster.java

License:Apache License

public static CompletableFuture<Channel> bootstrap(ModbusTcpMaster master, ModbusTcpMasterConfig config) {
    CompletableFuture<Channel> future = new CompletableFuture<>();

    Bootstrap bootstrap = new Bootstrap();

    config.getBootstrapConsumer().accept(bootstrap);

    bootstrap.group(config.getEventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) config.getTimeout().toMillis())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from w  w  w  .j a v a2s  . c o  m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(
                            new ModbusTcpCodec(new ModbusRequestEncoder(), new ModbusResponseDecoder()));
                    ch.pipeline().addLast(new ModbusTcpMasterHandler(master));
                }
            }).connect(config.getAddress(), config.getPort()).addListener((ChannelFuture f) -> {
                if (f.isSuccess()) {
                    future.complete(f.channel());
                } else {
                    future.completeExceptionally(f.cause());
                }
            });

    return future;
}