Example usage for io.netty.channel ChannelOption TCP_NODELAY

List of usage examples for io.netty.channel ChannelOption TCP_NODELAY

Introduction

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

Prototype

ChannelOption TCP_NODELAY

To view the source code for io.netty.channel ChannelOption TCP_NODELAY.

Click Source Link

Usage

From source file:nettyone.HttpRouterServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // This is an example router, it will be used at HttpRouterServerHandler.
    ////from  www .j a  v a  2 s .  co m
    // For simplicity of this example, route targets are just simple strings.
    // But you can make them classes, and at HttpRouterServerHandler once you
    // get a target class, you can create an instance of it and dispatch the
    // request to the instance etc.
    Router<String> router = new Router<String>().GET("/", "Index page").notFound("404 Not Found");
    System.out.println(router);

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

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE)
                .channel(NioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router));

        Channel ch = b.bind(PORT).sync().channel();
        System.out.println("Server started: http://127.0.0.1:" + PORT + '/');

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

From source file:nettyprivateprotocolclientdemo.NettyClient.java

public void connect(int port, String host) throws InterruptedException {
    try {/* w  ww . ja  va 2s .  c o m*/
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));
                        ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder());
                        ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                        ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler());
                        ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler());
                    } //initChannel()

                });

        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port),
                new InetSocketAddress(NettyConstant.LOCAL_IP, NettyConstant.LOCAL_PORT)).sync();

        future.channel().closeFuture().sync();
    } finally {
        executor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(5);
                    try {
                        connect(NettyConstant.PORT, NettyConstant.REMOTEIP);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            } //run()

        });

    } //try-finally

}

From source file:nettytimeclientdemo.TimeClient.java

/**
 *
 * @param port//  w  w  w  . j a  v  a2  s  .co m
 * @param host
 * @throws Exception
 */
public void connect(int port, String host) throws Exception {

    EventLoopGroup group = new NioEventLoopGroup();

    try {
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel c) throws Exception {
                        c.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        c.pipeline().addLast(new StringDecoder());
                        c.pipeline().addLast(new TimeClientHandler());
                    } //initChannel()

                });

        ChannelFuture future = bootstrap.connect(host, port).sync();

        future.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    } //try-finally
}

From source file:nikoladasm.aspark.server.ASparkServer.java

License:Open Source License

public void start() {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {//w  ww. ja  v  a2  s  . com
        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ServerInitializer(sslContext, maxContentLength, ipAddress, port, dispatcher,
                        exceptionMap, webSockets, serverName, pool))
                .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true);
        channel = server.bind(new InetSocketAddress(ipAddress, port)).sync().channel();
        started = true;
        latch.countDown();
        LOG.info("Netty server started");
    } catch (InterruptedException e) {
        LOG.error("Unexpected exception", e);
        bossGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
        workerGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
        started = false;
        latch.countDown();
    }
}

From source file:org.anhonesteffort.chnlzr.ChnlzrServer.java

License:Open Source License

@SuppressWarnings("unchecked")
private void run() throws InterruptedException {
    ListenableFuture sourceFuture = sourcePool.submit(source);
    Futures.addCallback(sourceFuture, criticalCallback);

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    try {//from  w  w  w.j a  va2  s  .c  om

        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, config.bufferHighWaterMark())
                .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, config.bufferLowWaterMark())
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast("idle state", new IdleStateHandler(0, 0,
                                config.idleStateThresholdMs(), TimeUnit.MILLISECONDS));
                        ch.pipeline().addLast("heartbeat", IdleStateHeartbeatWriter.INSTANCE);
                        ch.pipeline().addLast("encoder", BaseMessageEncoder.INSTANCE);
                        ch.pipeline().addLast("decoder", new BaseMessageDecoder());
                        ch.pipeline().addLast("handler",
                                new ServerHandler(config, resampling, sourceController));
                    }
                });

        ChannelFuture channelFuture = bootstrap.bind(config.serverPort()).sync();
        channelFuture.channel().closeFuture().sync();

    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        sourceFuture.cancel(true);
        sourcePool.shutdownNow();
    }

    System.exit(1);
}

From source file:org.anhonesteffort.p25.chnlzr.ChnlzrConnectionFactory.java

License:Open Source License

public ListenableFuture<ChnlzrConnectionHandler> create(HostId chnlzrHost) {
    SettableFuture<ChnlzrConnectionHandler> future = SettableFuture.create();
    ChnlzrConnectionHandler connection = new ChnlzrConnectionHandler(future);
    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(workerGroup).channel(channel).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectionTimeoutMs())
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, config.bufferHighWaterMark())
            .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, config.bufferLowWaterMark())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from  w  w  w.  j av a 2  s  .  co  m
                public void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast("idle state",
                            new IdleStateHandler(0, 0, config.idleStateThresholdMs(), TimeUnit.MILLISECONDS));
                    ch.pipeline().addLast("heartbeat", IdleStateHeartbeatWriter.INSTANCE);
                    ch.pipeline().addLast("encoder", BaseMessageEncoder.INSTANCE);
                    ch.pipeline().addLast("decoder", new BaseMessageDecoder());
                    ch.pipeline().addLast("connector", connection);
                }
            });

    bootstrap.connect(chnlzrHost.getHostname(), chnlzrHost.getPort()).addListener(connect -> {
        if (!connect.isSuccess())
            future.setException(new ConnectException("failed to connect to chnlzr"));
    });

    return future;
}

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptor.java

License:Apache License

public synchronized void start() throws Exception {
    if (channelClazz != null) {
        // Already started
        return;//from w  w w . j  av a 2s  .  c  o  m
    }

    if (useInvm) {
        channelClazz = LocalServerChannel.class;
        eventLoopGroup = new LocalEventLoopGroup();
    } else {
        int threadsToUse;

        if (nioRemotingThreads == -1) {
            // Default to number of cores * 3

            threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
        } else {
            threadsToUse = this.nioRemotingThreads;
        }
        channelClazz = NioServerSocketChannel.class;
        eventLoopGroup = new NioEventLoopGroup(threadsToUse,
                new ActiveMQThreadFactory("activemq-netty-threads", true, getThisClassLoader()));
    }

    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);
    final SSLContext context;
    if (sslEnabled) {
        try {
            if (keyStorePath == null && TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER.equals(keyStoreProvider))
                throw new IllegalArgumentException("If \"" + TransportConstants.SSL_ENABLED_PROP_NAME
                        + "\" is true then \"" + TransportConstants.KEYSTORE_PATH_PROP_NAME
                        + "\" must be non-null " + "unless an alternative \""
                        + TransportConstants.KEYSTORE_PROVIDER_PROP_NAME + "\" has been specified.");
            context = SSLSupport.createContext(keyStoreProvider, keyStorePath, keyStorePassword,
                    trustStoreProvider, trustStorePath, trustStorePassword);
        } catch (Exception e) {
            IllegalStateException ise = new IllegalStateException(
                    "Unable to create NettyAcceptor for " + host + ":" + port);
            ise.initCause(e);
            throw ise;
        }
    } else {
        context = null; // Unused
    }

    final AtomicBoolean warningPrinted = new AtomicBoolean(false);

    ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled) {
                SSLEngine engine = context.createSSLEngine();

                engine.setUseClientMode(false);

                if (needClientAuth)
                    engine.setNeedClientAuth(true);

                // setting the enabled cipher suites resets the enabled protocols so we need
                // to save the enabled protocols so that after the customer cipher suite is enabled
                // we can reset the enabled protocols if a customer protocol isn't specified
                String[] originalProtocols = engine.getEnabledProtocols();

                if (enabledCipherSuites != null) {
                    try {
                        engine.setEnabledCipherSuites(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites));
                    } catch (IllegalArgumentException e) {
                        ActiveMQServerLogger.LOGGER.invalidCipherSuite(SSLSupport
                                .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }

                if (enabledProtocols != null) {
                    try {
                        engine.setEnabledProtocols(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols));
                    } catch (IllegalArgumentException e) {
                        ActiveMQServerLogger.LOGGER.invalidProtocol(
                                SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols()));
                        throw e;
                    }
                } else {
                    engine.setEnabledProtocols(originalProtocols);
                }

                // Strip "SSLv3" from the current enabled protocols to address the POODLE exploit.
                // This recommendation came from http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html
                String[] protocols = engine.getEnabledProtocols();
                Set<String> set = new HashSet<>();
                for (String s : protocols) {
                    if (s.equals("SSLv3") || s.equals("SSLv2Hello")) {
                        if (!warningPrinted.get()) {
                            ActiveMQServerLogger.LOGGER.disallowedProtocol(s);
                        }
                        continue;
                    }
                    set.add(s);
                }
                warningPrinted.set(true);
                engine.setEnabledProtocols(set.toArray(new String[0]));

                SslHandler handler = new SslHandler(engine);

                pipeline.addLast("ssl", handler);
            }
            pipeline.addLast(protocolHandler.getProtocolDecoder());
        }
    };
    bootstrap.childHandler(factory);

    // Bind
    bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpReceiveBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    if (backlog != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, backlog);
    }
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    channelGroup = new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);

    if (httpUpgradeEnabled) {
        // the channel will be bound by the Web container and hand over after the HTTP Upgrade
        // handshake is successful
    } else {
        startServerChannels();

        paused = false;

        if (notificationService != null) {
            TypedProperties props = new TypedProperties();
            props.putSimpleStringProperty(new SimpleString("factory"),
                    new SimpleString(NettyAcceptorFactory.class.getName()));
            props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host));
            props.putIntProperty(new SimpleString("port"), port);
            Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props);
            notificationService.sendNotification(notification);
        }

        if (batchDelay > 0) {
            flusher = new BatchFlusher();

            batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay,
                    TimeUnit.MILLISECONDS);
        }

        ActiveMQServerLogger.LOGGER.startedAcceptor(host, port, protocolsString);
    }
}

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public synchronized void start() {
    if (channelClazz != null) {
        return;//from   w ww  . ja v a 2s .  c o  m
    }

    int threadsToUse;

    if (nioRemotingThreads == -1) {
        // Default to number of cores * 3

        threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
    } else {
        threadsToUse = this.nioRemotingThreads;
    }

    if (useNioGlobalWorkerPool) {
        channelClazz = NioSocketChannel.class;
        group = SharedNioEventLoopGroup.getInstance(threadsToUse);
    } else {
        channelClazz = NioSocketChannel.class;
        group = new NioEventLoopGroup(threadsToUse);
    }
    // if we are a servlet wrap the socketChannelFactory

    bootstrap = new Bootstrap();
    bootstrap.channel(channelClazz);
    bootstrap.group(group);

    bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay);

    if (connectTimeoutMillis != -1) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis);
    }
    if (tcpReceiveBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    channelGroup = new DefaultChannelGroup("activemq-connector", GlobalEventExecutor.INSTANCE);

    final SSLContext context;
    if (sslEnabled) {
        try {
            // HORNETQ-680 - override the server-side config if client-side system properties are set
            String realKeyStorePath = keyStorePath;
            String realKeyStoreProvider = keyStoreProvider;
            String realKeyStorePassword = keyStorePassword;
            if (System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME) != null) {
                realKeyStorePath = System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME) != null) {
                realKeyStorePassword = System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME);
            }

            if (System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME) != null) {
                realKeyStoreProvider = System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME) != null) {
                realKeyStorePath = System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME) != null) {
                realKeyStorePassword = System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME);
            }

            String realTrustStorePath = trustStorePath;
            String realTrustStoreProvider = trustStoreProvider;
            String realTrustStorePassword = trustStorePassword;
            if (System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME) != null) {
                realTrustStorePath = System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME) != null) {
                realTrustStorePassword = System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME);
            }

            if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME) != null) {
                realTrustStoreProvider = System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME) != null) {
                realTrustStorePath = System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME) != null) {
                realTrustStorePassword = System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME);
            }
            context = SSLSupport.createContext(realKeyStoreProvider, realKeyStorePath, realKeyStorePassword,
                    realTrustStoreProvider, realTrustStorePath, realTrustStorePassword);
        } catch (Exception e) {
            close();
            IllegalStateException ise = new IllegalStateException(
                    "Unable to create NettyConnector for " + host + ":" + port);
            ise.initCause(e);
            throw ise;
        }
    } else {
        context = null; // Unused
    }

    if (context != null && useServlet) {
        // TODO: Fix me
        //bootstrap.setOption("sslContext", context);
    }

    bootstrap.handler(new ChannelInitializer<Channel>() {
        public void initChannel(Channel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled && !useServlet) {
                SSLEngine engine = context.createSSLEngine();

                engine.setUseClientMode(true);

                engine.setWantClientAuth(true);

                // setting the enabled cipher suites resets the enabled protocols so we need
                // to save the enabled protocols so that after the customer cipher suite is enabled
                // we can reset the enabled protocols if a customer protocol isn't specified
                String[] originalProtocols = engine.getEnabledProtocols();

                if (enabledCipherSuites != null) {
                    try {
                        engine.setEnabledCipherSuites(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites));
                    } catch (IllegalArgumentException e) {
                        ActiveMQClientLogger.LOGGER.invalidCipherSuite(SSLSupport
                                .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }

                if (enabledProtocols != null) {
                    try {
                        engine.setEnabledProtocols(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols));
                    } catch (IllegalArgumentException e) {
                        ActiveMQClientLogger.LOGGER.invalidProtocol(
                                SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols()));
                        throw e;
                    }
                } else {
                    engine.setEnabledProtocols(originalProtocols);
                }

                SslHandler handler = new SslHandler(engine);

                pipeline.addLast(handler);
            }

            if (httpEnabled) {
                pipeline.addLast(new HttpRequestEncoder());

                pipeline.addLast(new HttpResponseDecoder());

                pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                pipeline.addLast(new HttpHandler());
            }

            if (httpUpgradeEnabled) {
                // prepare to handle a HTTP 101 response to upgrade the protocol.
                final HttpClientCodec httpClientCodec = new HttpClientCodec();
                pipeline.addLast(httpClientCodec);
                pipeline.addLast("http-upgrade", new HttpUpgradeHandler(pipeline, httpClientCodec));
            }

            protocolManager.addChannelHandlers(pipeline);

            pipeline.addLast(new ActiveMQClientChannelHandler(channelGroup, handler, new Listener()));
        }
    });

    if (batchDelay > 0) {
        flusher = new BatchFlusher();

        batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay,
                TimeUnit.MILLISECONDS);
    }

    ActiveMQClientLogger.LOGGER.debug("Started Netty Connector version " + TransportConstants.NETTY_VERSION);
}

From source file:org.apache.activemq.artemis.tests.integration.stomp.StompTestBase.java

License:Apache License

private void createBootstrap() {
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/* w ww  . j  a v  a 2s . co m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    addChannelHandlers(ch);
                }
            });

    // Start the client.
    try {
        channel = bootstrap.connect("localhost", port).sync().channel();
        handshake();
    } catch (InterruptedException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

}

From source file:org.apache.activemq.core.remoting.impl.netty.NettyAcceptor.java

License:Apache License

public synchronized void start() throws Exception {
    if (channelClazz != null) {
        // Already started
        return;//w  ww.  j a va  2s .c o m
    }

    if (useInvm) {
        channelClazz = LocalServerChannel.class;
        eventLoopGroup = new LocalEventLoopGroup();
    } else {
        int threadsToUse;

        if (nioRemotingThreads == -1) {
            // Default to number of cores * 3

            threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
        } else {
            threadsToUse = this.nioRemotingThreads;
        }
        channelClazz = NioServerSocketChannel.class;
        eventLoopGroup = new NioEventLoopGroup(threadsToUse,
                new ActiveMQThreadFactory("activemq-netty-threads", true, getThisClassLoader()));
    }

    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);
    final SSLContext context;
    if (sslEnabled) {
        try {
            if (keyStorePath == null && TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER.equals(keyStoreProvider))
                throw new IllegalArgumentException("If \"" + TransportConstants.SSL_ENABLED_PROP_NAME
                        + "\" is true then \"" + TransportConstants.KEYSTORE_PATH_PROP_NAME
                        + "\" must be non-null " + "unless an alternative \""
                        + TransportConstants.KEYSTORE_PROVIDER_PROP_NAME + "\" has been specified.");
            context = SSLSupport.createContext(keyStoreProvider, keyStorePath, keyStorePassword,
                    trustStoreProvider, trustStorePath, trustStorePassword);
        } catch (Exception e) {
            IllegalStateException ise = new IllegalStateException(
                    "Unable to create NettyAcceptor for " + host + ":" + port);
            ise.initCause(e);
            throw ise;
        }
    } else {
        context = null; // Unused
    }

    ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled) {
                SSLEngine engine = context.createSSLEngine();

                engine.setUseClientMode(false);

                if (needClientAuth)
                    engine.setNeedClientAuth(true);

                // setting the enabled cipher suites resets the enabled protocols so we need
                // to save the enabled protocols so that after the customer cipher suite is enabled
                // we can reset the enabled protocols if a customer protocol isn't specified
                String[] originalProtocols = engine.getEnabledProtocols();

                if (enabledCipherSuites != null) {
                    try {
                        engine.setEnabledCipherSuites(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites));
                    } catch (IllegalArgumentException e) {
                        ActiveMQServerLogger.LOGGER.invalidCipherSuite(SSLSupport
                                .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }

                if (enabledProtocols != null) {
                    try {
                        engine.setEnabledProtocols(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols));
                    } catch (IllegalArgumentException e) {
                        ActiveMQServerLogger.LOGGER.invalidProtocol(
                                SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols()));
                        throw e;
                    }
                } else {
                    engine.setEnabledProtocols(originalProtocols);
                }

                // Strip "SSLv3" from the current enabled protocols to address the POODLE exploit.
                // This recommendation came from http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html
                String[] protocols = engine.getEnabledProtocols();
                Set<String> set = new HashSet<>();
                for (String s : protocols) {
                    if (s.equals("SSLv3") || s.equals("SSLv2Hello")) {
                        ActiveMQServerLogger.LOGGER.disallowedProtocol(s);
                        continue;
                    }
                    set.add(s);
                }
                engine.setEnabledProtocols(set.toArray(new String[0]));

                SslHandler handler = new SslHandler(engine);

                pipeline.addLast("ssl", handler);
            }
            pipeline.addLast(protocolHandler.getProtocolDecoder());
        }
    };
    bootstrap.childHandler(factory);

    // Bind
    bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpReceiveBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    if (backlog != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, backlog);
    }
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    channelGroup = new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);

    if (httpUpgradeEnabled) {
        // the channel will be bound by the Web container and hand over after the HTTP Upgrade
        // handshake is successful
    } else {
        startServerChannels();

        paused = false;

        if (notificationService != null) {
            TypedProperties props = new TypedProperties();
            props.putSimpleStringProperty(new SimpleString("factory"),
                    new SimpleString(NettyAcceptorFactory.class.getName()));
            props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host));
            props.putIntProperty(new SimpleString("port"), port);
            Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props);
            notificationService.sendNotification(notification);
        }

        if (batchDelay > 0) {
            flusher = new BatchFlusher();

            batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay,
                    TimeUnit.MILLISECONDS);
        }

        ActiveMQServerLogger.LOGGER.startedNettyAcceptor(TransportConstants.NETTY_VERSION, host, port);
    }
}