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.mnxfst.stream.server.StreamAnalyzerServer.java

License:Apache License

public void run(final String configurationFilename, final int port) throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    StreamAnalyzerConfiguration streamAnalyzerConfiguration = mapper.readValue(new File(configurationFilename),
            StreamAnalyzerConfiguration.class);

    // set up  the actor runtime environment
    this.rootActorSystem = ActorSystem.create("streamanalyzer");

    this.componentRegistryRef = componentRegistryInitialization();
    pipelineInitialization(streamAnalyzerConfiguration.getPipelines());
    dispatcherInitialization(streamAnalyzerConfiguration.getDispatchers(), componentRegistryRef);
    listenerInitialization(streamAnalyzerConfiguration.getListeners(), componentRegistryRef);

    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from  w ww .  j a v  a 2  s  .c  o  m*/
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StreamAnalyzerStatsHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync(); // (7)

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

From source file:com.mobicage.rogerthat.plugins.news.NewsChannel.java

License:Apache License

public void connect() {
    if (TestUtils.isRunningTest()) {
        return;//  www. j  a v a 2 s .co m
    }
    T.NEWS();
    if (mIsConnected) {
        L.d("Already connected to news channel");
        return;
    } else if (!mService.getNetworkConnectivityManager().isConnected()) {
        L.d("Cannot connect to news channel: no internet connection.");
        return;
    } else if (mHost == null) {
        L.d("Not connecting to news channel because no host was found");
        return;
    } else if (mPort == -1) {
        L.d("Not connecting to news channel because no port was found");
        return;
    }
    mIsRetryingToConnect = true;
    L.d("Attemping to connect to news channel...");
    final SslContext sslCtx;
    if (CloudConstants.NEWS_CHANNEL_SSL) {
        try {
            if (CloudConstants.NEWS_CHANNEL_MUST_VALIDATE_SSL_CERTIFICATE) {
                TrustManagerFactory factory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                KeyStore keyStore = KeyStore.getInstance("AndroidCAStore"); // Gets the default system keystore
                keyStore.load(null, null);
                factory.init(keyStore);
                sslCtx = SslContextBuilder.forClient().trustManager(factory).build();
            } else {
                sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                        .build();
            }
        } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) {
            L.bug(e);
            return;
        }
    } else {
        sslCtx = null;
    }
    if (mEventLoopGroup == null) {
        mEventLoopGroup = new NioEventLoopGroup();
    }
    Bootstrap b = new Bootstrap();
    b.group(mEventLoopGroup).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) {
                        SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), mHost, mPort);
                        Future<Channel> handshakeDone = sslHandler.handshakeFuture();
                        handshakeDone.addListener(new GenericFutureListener<Future<? super Channel>>() {
                            @Override
                            public void operationComplete(Future<? super Channel> future) throws Exception {
                                authenticate();
                            }
                        });
                        p.addLast(sslHandler);
                    }
                    // decoder
                    p.addLast(new DelimiterBasedFrameDecoder(102400, Delimiters.lineDelimiter()));
                    p.addLast(new StringDecoder(Charset.forName("UTF-8")));

                    //encoder
                    p.addLast(new StringEncoder(Charset.forName("UTF-8")));
                    p.addLast(NewsChannel.this);
                }
            });
    // Bind and start to accept incoming connections.
    mChannel = b.connect(mHost, mPort).channel();
}

From source file:com.mobius.software.android.iotbroker.mqtt.net.TCPClient.java

License:Open Source License

public boolean init(final ConnectionListener listener) {
    if (channel == null) {
        bootstrap = new Bootstrap();
        loopGroup = new NioEventLoopGroup(workerThreads);
        bootstrap.group(loopGroup);//from  www. j a v a2s  . co m
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new MQDecoder());
                socketChannel.pipeline().addLast("handler", new MQHandler(listener));
                socketChannel.pipeline().addLast(new MQEncoder());
                socketChannel.pipeline().addLast(new ExceptionHandler(listener));
            }
        });
        bootstrap.remoteAddress(address);

        try {
            channelConnect = bootstrap.connect().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    return true;
}

From source file:com.mobius.software.mqtt.performance.controller.net.MqClientBootstrap.java

License:Open Source License

public void init(SocketAddress serverAddress) throws InterruptedException {
    this.serverAddress = serverAddress;
    if (pipelineInitialized.compareAndSet(false, true)) {
        bootstrap.group(loopGroup);//from  w  w w  . j  a v a 2s  .  c  o  m
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new Decoder());
                socketChannel.pipeline().addLast(new Encoder());
                socketChannel.pipeline().addLast("handler", new MqttHandler(clientListeners));
                socketChannel.pipeline().addLast(new ExceptionHandler());
            }
        });
        bootstrap.remoteAddress(serverAddress);
    }
}

From source file:com.mobius.software.mqtt.performance.controller.net.WsClientBootstrap.java

License:Open Source License

@Override
public void init(SocketAddress serverAddress) throws InterruptedException {
    this.serverAddress = serverAddress;
    if (pipelineInitialized.compareAndSet(false, true)) {
        try {//from ww w  .j a  v  a  2  s.  c o  m
            InetSocketAddress remote = (InetSocketAddress) serverAddress;
            URI uri = new URI("ws://" + remote.getHostString() + ":" + remote.getPort() + "/ws");

            bootstrap.group(loopGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.TCP_NODELAY, true);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast("http-codec", new HttpClientCodec());
                    socketChannel.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
                    socketChannel.pipeline().addLast("handler",
                            new WsClientHandler(
                                    WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13,
                                            null, false, EmptyHttpHeaders.INSTANCE, 1280000, true, true),
                                    clientListeners));
                    socketChannel.pipeline().addLast("compressor", WebSocketClientCompressionHandler.INSTANCE);
                    socketChannel.pipeline().addLast("exceptionHandler", exceptionHandler);
                }
            });
            bootstrap.remoteAddress(serverAddress);
        } catch (URISyntaxException e) {
            throw new InterruptedException(e.getMessage());
        }
    }
}

From source file:com.mongodb.connection.netty.NettyStream.java

License:Apache License

@Override
public void openAsync(final AsyncCompletionHandler<Void> handler) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup);/*from ww  w .  j  a  va 2s  . c om*/
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, settings.getConnectTimeout(MILLISECONDS));
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, settings.isKeepAlive());

    if (settings.getReceiveBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, settings.getReceiveBufferSize());
    }
    if (settings.getSendBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, settings.getSendBufferSize());
    }
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(final SocketChannel ch) throws Exception {
            if (sslSettings.isEnabled()) {
                SSLEngine engine = SSLContext.getDefault().createSSLEngine(address.getHost(),
                        address.getPort());
                engine.setUseClientMode(true);
                if (!sslSettings.isInvalidHostNameAllowed()) {
                    engine.setSSLParameters(enableHostNameVerification(engine.getSSLParameters()));
                }
                ch.pipeline().addFirst("ssl", new SslHandler(engine, false));
            }
            ch.pipeline().addLast("readTimeoutHandler",
                    new ReadTimeoutHandler(settings.getReadTimeout(MILLISECONDS), MILLISECONDS));
            ch.pipeline().addLast(new InboundBufferHandler());
        }
    });
    final ChannelFuture channelFuture = bootstrap.connect(address.getHost(), address.getPort());
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = channelFuture.channel();
                handler.completed(null);
            } else {
                handler.failed(future.cause());
            }
        }
    });
}

From source file:com.moshi.receptionist.remoting.netty.NettyRemotingClient.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyClientConfig.getClientWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override/* ww w  .  ja  v  a2s  . c om*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap handler = this.bootstrap.group(this.eventLoopGroup).channel(NioSocketChannel.class)//
            //
            .option(ChannelOption.TCP_NODELAY, true)
            //
            .option(ChannelOption.SO_SNDBUF, NettySystemConfig.SocketSndbufSize)
            //
            .option(ChannelOption.SO_RCVBUF, NettySystemConfig.SocketRcvbufSize)
            //
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(//
                            defaultEventExecutorGroup, //
                            new NettyEncoder(), //
                            new NettyDecoder(), //
                            new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), //
                            new NettyConnetManageHandler(), //
                            new NettyClientHandler());
                }
            });

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingClient.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }
}

From source file:com.moshi.receptionist.remoting.netty.NettyRemotingServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override//from  w  ww .  j a  va 2 s  .  c  om
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroup, new NioEventLoopGroup())
                    .channel(NioServerSocketChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //
                    .childOption(ChannelOption.SO_SNDBUF, NettySystemConfig.SocketSndbufSize)
                    //
                    .childOption(ChannelOption.SO_RCVBUF, NettySystemConfig.SocketRcvbufSize)

                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new NettyEncoder(), //
                                    new NettyDecoder(), //
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //
                                    new NettyConnetManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (NettySystemConfig.NettyPooledByteBufAllocatorEnable) {
        // ????
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
        ;
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingServer.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
}

From source file:com.mpush.netty.client.NettyClient.java

License:Apache License

@Override
public void start(final Listener listener) {
    if (started.compareAndSet(false, true)) {
        Bootstrap bootstrap = new Bootstrap();
        workerGroup = new NioEventLoopGroup();
        bootstrap.group(workerGroup)//
                .option(ChannelOption.TCP_NODELAY, true)//
                .option(ChannelOption.SO_REUSEADDR, true)//
                .option(ChannelOption.SO_KEEPALIVE, true)//
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
                .channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override/*www .  j a  v  a  2 s.  c  o m*/
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    if (listener != null)
                        listener.onSuccess(port);
                    LOGGER.info("start netty client success, host={}, port={}", host, port);
                } else {
                    if (listener != null)
                        listener.onFailure(future.cause());
                    LOGGER.error("start netty client failure, host={}, port={}", host, port, future.cause());
                }
            }
        });
    } else {
        listener.onFailure(new ServiceException("client has started!"));
    }
}

From source file:com.mpush.netty.client.NettyTCPClient.java

License:Apache License

private void createClient(Listener listener, EventLoopGroup workerGroup,
        ChannelFactory<? extends Channel> channelFactory) {
    this.workerGroup = workerGroup;
    this.bootstrap = new Bootstrap();
    bootstrap.group(workerGroup)//
            .option(ChannelOption.SO_REUSEADDR, true)//
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
            .channelFactory(channelFactory);
    bootstrap.handler(new ChannelInitializer<Channel>() { // (4)
        @Override/*from   w ww.  j  a va  2  s.  c  om*/
        public void initChannel(Channel ch) throws Exception {
            initPipeline(ch.pipeline());
        }
    });
    initOptions(bootstrap);
    listener.onSuccess();
}