Example usage for io.netty.channel ChannelOption SO_REUSEADDR

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

Introduction

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

Prototype

ChannelOption SO_REUSEADDR

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

Click Source Link

Usage

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

License:Apache License

public synchronized void start() {
    if (channelClazz != null) {
        return;// w w  w  .  j a v  a2  s .co 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, new UnpooledByteBufAllocator(false));
    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.camel.component.netty4.ClientModeTCPNettyServerBootstrapFactory.java

License:Apache License

protected void startServerBootstrap() throws Exception {
    // prefer using explicit configured thread pools

    EventLoopGroup wg = configuration.getWorkerGroup();

    if (wg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerGroup = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount())
                .withName("NettyServerTCPWorker").build();
        wg = workerGroup;//from   w  w  w .j  a  va2 s  . co m
    }

    clientBootstrap = new Bootstrap();
    clientBootstrap.channel(NioSocketChannel.class);
    clientBootstrap.group(wg);
    clientBootstrap.option(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
    clientBootstrap.option(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
    clientBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

    LOG.debug("Created ClientBootstrap {}", clientBootstrap);
    clientBootstrap.handler(pipelineFactory);
    ChannelFuture channelFuture = clientBootstrap
            .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
    if (LOG.isDebugEnabled()) {
        LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}",
                new Object[] { configuration.getHost(), configuration.getPort(), clientBootstrap });
    }
    LOG.info("ClientModeServerBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
    channel = openChannel(channelFuture);

}

From source file:org.apache.camel.component.netty4.NettyProducer.java

License:Apache License

protected ChannelFuture openConnection() throws Exception {
    ChannelFuture answer;/*from   www  . ja  v a 2  s.co  m*/

    if (isTcp()) {
        // its okay to create a new bootstrap for each new channel
        Bootstrap clientBootstrap = new Bootstrap();
        clientBootstrap.channel(NioSocketChannel.class);
        clientBootstrap.group(getWorkerGroup());
        clientBootstrap.option(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
        clientBootstrap.option(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
        clientBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
        clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

        //TODO need to check it later
        // set any additional netty options
        /*
        if (configuration.getOptions() != null) {
        for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
            clientBootstrap.setOption(entry.getKey(), entry.getValue());
        }
        }*/

        // set the pipeline factory, which creates the pipeline for each newly created channels
        clientBootstrap.handler(pipelineFactory);
        answer = clientBootstrap
                .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}",
                    new Object[] { configuration.getHost(), configuration.getPort(), clientBootstrap });
        }
        return answer;
    } else {
        // its okay to create a new bootstrap for each new channel
        Bootstrap connectionlessClientBootstrap = new Bootstrap();
        connectionlessClientBootstrap.channel(NioDatagramChannel.class);
        connectionlessClientBootstrap.group(getWorkerGroup());
        connectionlessClientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                configuration.getConnectTimeout());
        connectionlessClientBootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
        connectionlessClientBootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
        connectionlessClientBootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());

        //TODO need to check it later
        // set any additional netty options
        /*
        if (configuration.getOptions() != null) {
        for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
            connectionlessClientBootstrap.setOption(entry.getKey(), entry.getValue());
        }
        }*/

        // set the pipeline factory, which creates the pipeline for each newly created channels
        connectionlessClientBootstrap.handler(pipelineFactory);
        // bind and store channel so we can close it when stopping
        ChannelFuture channelFuture = connectionlessClientBootstrap.bind(new InetSocketAddress(0));
        channelFuture.awaitUninterruptibly();
        Channel channel = channelFuture.channel();
        allChannels.add(channel);
        answer = connectionlessClientBootstrap
                .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new UDP client bootstrap connecting to {}:{} with options: {}", new Object[] {
                    configuration.getHost(), configuration.getPort(), connectionlessClientBootstrap });
        }
        return answer;
    }
}

From source file:org.apache.camel.component.netty4.SingleTCPNettyServerBootstrapFactory.java

License:Apache License

protected void startServerBootstrap() {
    // prefer using explicit configured thread pools
    EventLoopGroup bg = configuration.getBossGroup();
    EventLoopGroup wg = configuration.getWorkerGroup();

    if (bg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        bossGroup = new NettyServerBossPoolBuilder().withBossCount(configuration.getBossCount())
                .withName("NettyServerTCPBoss").build();
        bg = bossGroup;/*from www  . ja  v a 2  s.  co m*/
    }
    if (wg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerGroup = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount())
                .withName("NettyServerTCPWorker").build();
        wg = workerGroup;
    }

    //channelFactory = new NioServerSocketChannelFactory(bg, wg);

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bg, wg).channel(NioServerSocketChannel.class);
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
    if (configuration.getBacklog() > 0) {
        serverBootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());
    }

    // TODO set any additional netty options and child options
    /*if (configuration.getOptions() != null) {
    for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
        serverBootstrap.setOption(entry.getKey(), entry.getValue());
    }
    }*/

    // set the pipeline factory, which creates the pipeline for each newly created channels
    serverBootstrap.childHandler(pipelineFactory);

    LOG.debug("Created ServerBootstrap {}", serverBootstrap);

    LOG.info("ServerBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
    ChannelFuture channelFutrue = serverBootstrap
            .bind(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
    channelFutrue.awaitUninterruptibly();
    channel = channelFutrue.channel();
    // to keep track of all channels in use
    allChannels.add(channel);
}

From source file:org.apache.camel.component.netty4.SingleUDPNettyServerBootstrapFactory.java

License:Apache License

protected void startServerBootstrap() throws Exception {
    // create non-shared worker pool
    EventLoopGroup wg = configuration.getWorkerGroup();
    if (wg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerGroup = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount())
                .withName("NettyServerTCPWorker").build();
        wg = workerGroup;//  ww w .j  av a  2s.  c om
    }

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(wg).channel(NioDatagramChannel.class);
    // We cannot set the child option here      
    bootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    bootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
    bootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());
    bootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

    // TODO need to find the right setting of below option
    // only set this if user has specified
    /*
    if (configuration.getReceiveBufferSizePredictor() > 0) {
    bootstrap.setOption("receiveBufferSizePredictorFactory",
            new FixedReceiveBufferSizePredictorFactory(configuration.getReceiveBufferSizePredictor()));
    }*/

    if (configuration.getBacklog() > 0) {
        bootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());
    }

    //TODO need to check the additional netty options
    /*
    if (configuration.getOptions() != null) {
    for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
        connectionlessBootstrap.setOption(entry.getKey(), entry.getValue());
    }
    }*/

    LOG.debug("Created ConnectionlessBootstrap {}", bootstrap);

    // set the pipeline factory, which creates the pipeline for each newly created channels
    bootstrap.handler(pipelineFactory);

    InetSocketAddress hostAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    SubnetUtils multicastSubnet = new SubnetUtils(MULTICAST_SUBNET);

    if (multicastSubnet.getInfo().isInRange(configuration.getHost())) {
        ChannelFuture channelFuture = bootstrap.bind(hostAddress);
        channelFuture.awaitUninterruptibly();
        channel = channelFuture.channel();
        DatagramChannel datagramChannel = (DatagramChannel) channel;
        String networkInterface = configuration.getNetworkInterface() == null ? LOOPBACK_INTERFACE
                : configuration.getNetworkInterface();
        multicastNetworkInterface = NetworkInterface.getByName(networkInterface);
        ObjectHelper.notNull(multicastNetworkInterface,
                "No network interface found for '" + networkInterface + "'.");
        LOG.info("ConnectionlessBootstrap joining {}:{} using network interface: {}", new Object[] {
                configuration.getHost(), configuration.getPort(), multicastNetworkInterface.getName() });
        datagramChannel.joinGroup(hostAddress, multicastNetworkInterface).syncUninterruptibly();
        allChannels.add(datagramChannel);
    } else {
        LOG.info("ConnectionlessBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
        ChannelFuture channelFuture = bootstrap.bind(hostAddress);
        channelFuture.awaitUninterruptibly();
        channel = channelFuture.channel();
        allChannels.add(channel);
    }
}

From source file:org.apache.cxf.transport.http.netty.server.NettyHttpServerEngine.java

License:Apache License

protected Channel startServer() {

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_REUSEADDR, true);

    // Set up the event pipeline factory.
    servletPipeline = new NettyHttpServletPipelineFactory(tlsServerParameters, sessionSupport,
            threadingParameters.getThreadPoolSize(), maxChunkContentSize, handlerMap, this);
    // Start the servletPipeline's timer
    servletPipeline.start();/*from   w  ww.j a  v  a 2 s. c o  m*/
    bootstrap.childHandler(servletPipeline);
    InetSocketAddress address = null;
    if (host == null) {
        address = new InetSocketAddress(port);
    } else {
        address = new InetSocketAddress(host, port);
    }
    // Bind and start to accept incoming connections.
    try {
        return bootstrap.bind(address).sync().channel();
    } catch (InterruptedException ex) {
        // do nothing here
        return null;
    }
}

From source file:org.apache.drill.exec.rpc.BasicClient.java

License:Apache License

public BasicClient(RpcConfig rpcMapping, ByteBufAllocator alloc, EventLoopGroup eventLoopGroup, T handshakeType,
        Class<HANDSHAKE_RESPONSE> responseClass, Parser<HANDSHAKE_RESPONSE> handshakeParser) {
    super(rpcMapping);
    this.responseClass = responseClass;
    this.handshakeType = handshakeType;
    this.handshakeParser = handshakeParser;
    final long timeoutInMillis = rpcMapping.hasTimeout()
            ? (long) (rpcMapping.getTimeout() * 1000.0 * PERCENT_TIMEOUT_BEFORE_SENDING_PING)
            : -1;/*from  w  ww  .  j av  a  2s .  co  m*/
    this.pingHandler = rpcMapping.hasTimeout() ? new IdlePingHandler(timeoutInMillis) : null;

    b = new Bootstrap() //
            .group(eventLoopGroup) //
            .channel(TransportCheck.getClientSocketChannel()) //
            .option(ChannelOption.ALLOCATOR, alloc) //
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30 * 1000).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_RCVBUF, 1 << 17) //
            .option(ChannelOption.SO_SNDBUF, 1 << 17) //
            .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // logger.debug("initializing client connection.");
                    connection = initRemoteConnection(ch);

                    ch.closeFuture().addListener(getCloseHandler(ch, connection));

                    final ChannelPipeline pipe = ch.pipeline();

                    pipe.addLast("protocol-decoder", getDecoder(connection.getAllocator()));
                    pipe.addLast("message-decoder", new RpcDecoder("c-" + rpcConfig.getName()));
                    pipe.addLast("protocol-encoder", new RpcEncoder("c-" + rpcConfig.getName()));
                    pipe.addLast("handshake-handler", new ClientHandshakeHandler(connection));

                    if (pingHandler != null) {
                        pipe.addLast("idle-state-handler", pingHandler);
                    }

                    pipe.addLast("message-handler", new InboundHandler(connection));
                    pipe.addLast("exception-handler", new RpcExceptionHandler<R>(connection));
                }
            }); //

    // if(TransportCheck.SUPPORTS_EPOLL){
    // b.option(EpollChannelOption.SO_REUSEPORT, true); //
    // }
}

From source file:org.apache.drill.exec.rpc.BasicServer.java

License:Apache License

public BasicServer(final RpcConfig rpcMapping, ByteBufAllocator alloc, EventLoopGroup eventLoopGroup) {
    super(rpcMapping);
    this.eventLoopGroup = eventLoopGroup;

    b = new ServerBootstrap().channel(TransportCheck.getServerSocketChannel())
            .option(ChannelOption.SO_BACKLOG, 1000).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30 * 1000)
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_RCVBUF, 1 << 17).option(ChannelOption.SO_SNDBUF, 1 << 17)
            .group(eventLoopGroup) //
            .childOption(ChannelOption.ALLOCATOR, alloc)

            // .handler(new LoggingHandler(LogLevel.INFO))

            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override// w w w . j a  v  a  2  s  .co m
                protected void initChannel(SocketChannel ch) throws Exception {
                    //            logger.debug("Starting initialization of server connection.");
                    C connection = initRemoteConnection(ch);
                    ch.closeFuture().addListener(getCloseHandler(ch, connection));

                    final ChannelPipeline pipe = ch.pipeline();
                    pipe.addLast("protocol-decoder",
                            getDecoder(connection.getAllocator(), getOutOfMemoryHandler()));
                    pipe.addLast("message-decoder", new RpcDecoder("s-" + rpcConfig.getName()));
                    pipe.addLast("protocol-encoder", new RpcEncoder("s-" + rpcConfig.getName()));
                    pipe.addLast("handshake-handler", getHandshakeHandler(connection));

                    if (rpcMapping.hasTimeout()) {
                        pipe.addLast(TIMEOUT_HANDLER,
                                new LogggingReadTimeoutHandler(connection, rpcMapping.getTimeout()));
                    }

                    pipe.addLast("message-handler", new InboundHandler(connection));
                    pipe.addLast("exception-handler", new RpcExceptionHandler<C>(connection));

                    connect = true;
                    //            logger.debug("Server connection initialization completed.");
                }
            });

    //     if(TransportCheck.SUPPORTS_EPOLL){
    //       b.option(EpollChannelOption.SO_REUSEPORT, true); //
    //     }
}

From source file:org.apache.dubbo.qos.server.Server.java

License:Apache License

/**
 * start server, bind port/* w  w  w . j a  v  a  2  s.  c o  m*/
 */
public void start() throws Throwable {
    if (!started.compareAndSet(false, true)) {
        return;
    }
    boss = new NioEventLoopGroup(1, new DefaultThreadFactory("qos-boss", true));
    worker = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-worker", true));
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(boss, worker);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    serverBootstrap.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new QosProcessHandler(welcome, acceptForeignIp));
        }
    });
    try {
        serverBootstrap.bind(port).sync();
        logger.info("qos-server bind localhost:" + port);
    } catch (Throwable throwable) {
        logger.error("qos-server can not bind localhost:" + port, throwable);
        throw throwable;
    }
}

From source file:org.apache.dubbo.remoting.transport.netty4.NettyServer.java

License:Apache License

/**
 * Init and start netty server/*  w  ww .j  a  v a  2s. com*/
 *
 * @throws Throwable
 */
@Override
protected void doOpen() throws Throwable {
    bootstrap = new ServerBootstrap();

    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    workerGroup = new NioEventLoopGroup(
            getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
            new DefaultThreadFactory("NettyServerWorker", true));

    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    // FIXME: should we use getTimeout()?
                    int idleTimeout = UrlUtils.getIdleTimeout(getUrl());
                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                            .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                            .addLast("server-idle-handler",
                                    new IdleStateHandler(0, 0, idleTimeout, MILLISECONDS))
                            .addLast("handler", nettyServerHandler);
                }
            });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();

}