Example usage for io.netty.channel ChannelOption SO_BACKLOG

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

Introduction

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

Prototype

ChannelOption SO_BACKLOG

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

Click Source Link

Usage

From source file:nettyTest.httpSsl.oneWay.HttpsHelloWorldServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//ww  w .  j  ava 2 s  .co m
        File certificate = new File(
                HttpsHelloWorldServer.class.getClassLoader().getResource("nettyca/server.crt").getFile());
        File privateKey = new File(
                HttpsHelloWorldServer.class.getClassLoader().getResource("nettyca/server.pem").getFile());
        sslCtx = SslContextBuilder.forServer(certificate, privateKey).build();
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpsHelloWorldServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:"
                + PORT + '/');

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

From source file:nettyTimeServerDemo.TimeServer.java

/**
 *
 * @param port//w ww.ja v  a  2s  .  c  o m
 * @throws Exception
 */
public void bind(int port) throws Exception {

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

    try {

        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).childHandler(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 TimeServerHandler());
                    } //initChannel()

                });

        ChannelFuture future = bootstrap.bind(port).sync();

        future.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.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 {/*from   ww w.j a va 2s  . c o m*/
        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.acmsl.katas.antlr4netty.InterpreterServer.java

License:Open Source License

/**
 * Launches the server to accept incoming requests on given port.
 * @param port the port./*from www. j a v  a 2  s  .c o  m*/
 * @return the {@link ChannelFuture} when the server stops accepting connections.
 */
@NotNull
public ChannelFuture listen(final int port) {
    @NotNull
    final ChannelFuture result;

    @NotNull
    final NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    @NotNull
    final NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                /**
                 * {@inheritDoc}
                 */
                @Override
                protected void initChannel(@NotNull final SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new InterpreterServerChannelHandler());
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    result = wrap(bootstrap.bind(port), bossGroup, workerGroup);

    return result;
}

From source file:org.acmsl.queryj.debugging.netty.NettyServerDebuggingService.java

License:Open Source License

/**
 * Launches the server./*from  w  w w  .jav a 2s . c o m*/
 * @param port the port.
 * @param handler the {@link ChannelHandlerAdapter handler} to handle incoming connections.
 * @return the {@link ChannelFuture}.
 * @throws InterruptedException if the server gets interrupted.
 * @throws IOException if the socket cannot be bound.
 */
@NotNull
protected ChannelFuture launchServer(final int port, @NotNull final ChannelHandlerAdapter handler)
        throws InterruptedException, IOException {
    @NotNull
    final ChannelFuture result;

    @Nullable
    ChannelFuture aux = null;

    @NotNull
    final EventLoopGroup bossGroup = new NioEventLoopGroup();
    setEventLoopGroup(bossGroup);
    @NotNull
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        @NotNull
        final ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    /**
                     * {@inheritDoc}
                     */
                    @Override
                    public void initChannel(@NotNull final SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(handler);
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        aux = 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.
        //            result.channel().closeFuture().sync();
    } catch (@NotNull final Throwable throwable) {
        LogFactory.getLog(NettyServerDebuggingService.class).fatal("Cannot run the template debugging server",
                throwable);
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

    if (aux == null) {
        throw new RuntimeException("Cannot run server");
    } else {
        result = aux;
    }

    return result;
}

From source file:org.anhonesteffort.chnlbrkr.ChnlBrkrServer.java

License:Open Source License

public void run() throws InterruptedException {
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    IdleChnlzrConnectionFactory idleFactory = new IdleChnlzrConnectionFactory(config);
    IdleChnlzrController idleController = new IdleChnlzrController(idleFactory);
    ChannelStreamerFactory streamFactory = new ChannelStreamerFactory(config);

    Optional<RedisClient> redisClient = (redisUri.isPresent()) ? Optional.of(RedisClient.create(redisUri.get()))
            : Optional.<RedisClient>empty();

    BrkrList brkrList = new BrkrList(config, hostId, workerGroup, redisClient);
    Optional<ChnlzrIdPubSub> chnlzrPubSub = (redisClient.isPresent())
            ? Optional.of(new ChnlzrIdPubSub(config, redisClient.get(), idleController))
            : Optional.empty();/*from w w  w .  j  av  a  2 s . c om*/

    try {

        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, 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("brkrlist", brkrList);
                        ch.pipeline().addLast("handler",
                                new ServerHandler(config, idleController, streamFactory, chnlzrPubSub));
                    }
                });

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

    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        if (redisClient.isPresent()) {
            redisClient.get().shutdown();
        }
    }
}

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   ww  w .j  a v a2  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.aotorrent.client.TorrentClient.java

License:Apache License

@Override
public void run() {
    // Configure the server.
    try {/* w  ww.  j  a  v a2  s .c om*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new InboundChannelInitializer(this))
                .childAttr(AttributeKey.valueOf("torrentEngines"), torrentEngines);

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

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

From source file:org.aotorrent.tracker.TorrentTracker.java

License:Apache License

@Override
public void run() {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//w w w .  j  ava 2s . c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new TrackerChannelInitializer(torrents));

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

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        LOGGER.error("Interrupted", e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

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;//  ww  w  .ja v a 2 s . co 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);
    }
}