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.navercorp.nbasearc.gcp.PhysicalConnection.java

License:Apache License

static PhysicalConnection create(String ip, int port, SingleThreadEventLoop eventLoop, Gateway gw,
        int reconnectInterval) {
    final PhysicalConnection pc = new PhysicalConnection(ip, port, eventLoop, gw, reconnectInterval);

    pc.b.group(eventLoop.getEventLoopGroup()).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_LINGER, 0)
            .option(ChannelOption.SO_SNDBUF, SOCKET_BUFFER).option(ChannelOption.SO_RCVBUF, SOCKET_BUFFER)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from   w ww . j  a  v  a  2 s .com
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(pc.new PhysicalConnectionHandler());
                }
            });

    return pc;
}

From source file:com.navercorp.pinpoint.plugin.netty.NettyIT.java

License:Apache License

public Bootstrap client() {
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*  w  ww .  j a  va  2s.  c  om*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new HttpClientCodec());
                    ch.pipeline().addLast(new HttpObjectAggregator(65535));
                }
            });
    return bootstrap;
}

From source file:com.net.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO/*from w  w w. ja  v  a  2  s. c  om*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    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 IOException {
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                    ch.pipeline().addLast(new ServerHandler(redisTemplate));
                }
            });

    // ???
    b.bind(ContantUtil.port).sync();
    System.out.println("Netty server start ok : " + ("127.0.0.1" + " : " + ContantUtil.port));
}

From source file:com.netflix.hystrix.examples.reactivesocket.HystrixMetricsReactiveSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.out.println("Starting HystrixMetricsReactiveSocketServer...");

    final ReactiveSocketServerHandler handler = ReactiveSocketServerHandler
            .create((setupPayload, rs) -> new EventStreamRequestHandler());

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {//from   w  w  w. j  a va2  s. co m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(handler);
                    }
                });
        Channel localhost = b.bind("127.0.0.1", 8025).sync().channel();

        executeCommands();
        localhost.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.netty.fileTest.file.FileReaderClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from ww w. java2s . c  o  m
        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();
                        p.addLast(new FileReaderClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect("127.0.0.1", 8007).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.netty.fileTest.file.FileSenderServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from  ww  w  .j  a  va2 s.  com
        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 StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(8192),
                                new StringDecoder(CharsetUtil.UTF_8), new ChunkedWriteHandler(),
                                new FileSenderServerHandler());
                    }
                });

        // 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.newlandframework.avatarmq.broker.server.AvatarMQBrokerServer.java

License:Apache License

public void init() {
    try {/*from  w  ww  .ja  v a  2  s.  c  om*/
        handler = new MessageBrokerHandler().buildConsumerHook(new ConsumerMessageHook())
                .buildProducerHook(new ProducerMessageHook());

        boss = new NioEventLoopGroup(1, threadBossFactory);

        workers = new NioEventLoopGroup(parallel, threadWorkerFactory, NettyUtil.getNioSelectorProvider());

        KryoCodecUtil util = new KryoCodecUtil(KryoPoolFactory.getKryoPoolInstance());

        bootstrap = new ServerBootstrap();

        bootstrap.group(boss, workers).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_SNDBUF, nettyClustersConfig.getClientSocketSndBufSize())
                .option(ChannelOption.SO_RCVBUF, nettyClustersConfig.getClientSocketRcvBufSize())
                .handler(new LoggingHandler(LogLevel.INFO)).localAddress(serverIpAddr)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(defaultEventExecutorGroup, new MessageObjectEncoder(util),
                                new MessageObjectDecoder(util), handler);
                    }
                });

        super.init();
    } catch (IOException ex) {
        Logger.getLogger(AvatarMQBrokerServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.newlandframework.avatarmq.netty.MessageConnectFactory.java

License:Apache License

public void init() {
    try {/*from www  . j ava  2 s.  c  o m*/
        defaultEventExecutorGroup = new DefaultEventExecutorGroup(NettyClustersConfig.getWorkerThreads(),
                threadFactory);
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    public void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(defaultEventExecutorGroup);
                        channel.pipeline().addLast(new MessageObjectEncoder(util));
                        channel.pipeline().addLast(new MessageObjectDecoder(util));
                        channel.pipeline().addLast(messageHandler);
                    }
                }).option(ChannelOption.SO_SNDBUF, nettyClustersConfig.getClientSocketSndBufSize())
                .option(ChannelOption.SO_RCVBUF, nettyClustersConfig.getClientSocketRcvBufSize())
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, false);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java

License:Apache License

void configureNetty() {
    Map<String, ChannelOption<Object>> optionMap = new HashMap<String, ChannelOption<Object>>();
    for (Field field : ChannelOption.class.getDeclaredFields()) {
        if (field.getType().isAssignableFrom(ChannelOption.class)) {
            field.setAccessible(true);/*from  ww  w  .  j a v a 2  s  .c  o  m*/
            try {
                optionMap.put(field.getName(), (ChannelOption<Object>) field.get(null));
            } catch (IllegalAccessException ex) {
                throw new Error(ex);
            }
        }
    }

    if (asyncHttpProviderConfig != null) {
        for (Entry<String, Object> entry : asyncHttpProviderConfig.propertiesSet()) {
            ChannelOption<Object> key = optionMap.get(entry.getKey());
            Object value = entry.getValue();
            plainBootstrap.option(key, value);
            webSocketBootstrap.option(key, value);
            secureBootstrap.option(key, value);
            secureWebSocketBootstrap.option(key, value);
        }
    }

    plainBootstrap.handler(createPlainPipelineFactory());
    // DefaultChannelFuture.setUseDeadLockChecker(false);

    if (asyncHttpProviderConfig != null) {
        executeConnectAsync = asyncHttpProviderConfig.isAsyncConnect();
        if (!executeConnectAsync) {
            // DefaultChannelFuture.setUseDeadLockChecker(true);
        }
    }

    webSocketBootstrap.handler(new ChannelInitializer() {
        /* @Override */
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("ws-decoder", new HttpResponseDecoder());
            pipeline.addLast("ws-encoder", new HttpRequestEncoder());
            pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
        }
    });
}

From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java

License:Apache License

protected ChannelInitializer createPlainPipelineFactory() {
    return new ChannelInitializer() {

        /* @Override */
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast(HTTP_HANDLER, newHttpClientCodec());

            if (config.getRequestCompressionLevel() > 0) {
                pipeline.addLast("deflater", new HttpContentCompressor(config.getRequestCompressionLevel()));
            }//from w w  w  . java 2s. co  m

            if (config.isCompressionEnabled()) {
                pipeline.addLast("inflater", new HttpContentDecompressor());
            }
            pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
            pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
        }
    };
}