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:org.gamejam.gc.fartroulette.WhoFartedServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*w w  w.  ja  v a  2s  .co  m*/
        final ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpRequestDecoder(), new HttpObjectAggregator(65536),
                                new HttpResponseEncoder(),
                                new HttpStaticFileServerHandler(true, "websocket", "api"),
                                new WebSocketServerProtocolHandler("/websocket"),
                                new WebSocketFrameHandler(s_allChannels, s_elevatorData));

                    }
                }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_TIMEOUT, 100)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        //loadDummyData();

        runUpdaterThread();

        runGame();

        final Channel ch = sb.bind(port).sync().channel();
        System.out.println("Web socket server started at port " + port);

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

From source file:org.gameoss.gridcast.p2p.node.NodeServer.java

License:Apache License

public void initialize(final String host, final int port, final EventLoopGroup bossGroup,
        final EventLoopGroup workerGroup, final MessageRegistry messageRegistry,
        final ChannelInboundHandlerAdapter channelListener) {
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(bossGroup, workerGroup);//from w  ww  . ja  v  a  2s  .c  o  m
    boot.channel(NioServerSocketChannel.class);
    boot.option(ChannelOption.SO_BACKLOG, 32);
    boot.childOption(ChannelOption.SO_KEEPALIVE, true);
    boot.childOption(ChannelOption.TCP_NODELAY, true);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();

            // encoders
            p.addLast(new LengthFieldPrepender(4));
            p.addLast(new ProtostuffEncoder(messageRegistry));

            // decoders
            p.addLast(new LengthFieldBasedFrameDecoder(0x100000, 0, 4, 0, 4));
            p.addLast(new ProtostuffDecoder(messageRegistry));
            p.addLast(channelListener);
        }
    });

    // start accepting connection
    try {
        if (host == null) {
            acceptChannel = boot.bind(port).sync().channel();
        } else {
            acceptChannel = boot.bind(host, port).sync().channel();
        }
    } catch (InterruptedException e) {
        logger.error("Binding to port {} failed", port, e);
    }

}

From source file:org.glassfish.jersey.netty.httpserver.NettyHttpContainerProvider.java

License:Open Source License

/**
 * Create and start Netty server.//from   ww w .  j  ava2  s  . c om
 *
 * @param baseUri       base uri.
 * @param configuration Jersey configuration.
 * @param sslContext    Netty SSL context (can be null).
 * @param block         when {@code true}, this method will block until the server is stopped. When {@code false}, the
 *                      execution will
 *                      end immediately after the server is started.
 * @return Netty channel instance.
 * @throws ProcessingException when there is an issue with creating new container.
 */
public static Channel createServer(final URI baseUri, final ResourceConfig configuration, SslContext sslContext,
        final boolean block) throws ProcessingException {

    // Configure the server.
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    final NettyHttpContainer container = new NettyHttpContainer(configuration);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new JerseyServerInitializer(baseUri, sslContext, container));

        int port = getPort(baseUri);

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

        ch.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                container.getApplicationHandler().onShutdown(container);

                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        });

        if (block) {
            ch.closeFuture().sync();
            return ch;
        } else {
            return ch;
        }
    } catch (InterruptedException e) {
        throw new ProcessingException(e);
    }
}

From source file:org.glassfish.jersey.netty.httpserver.NettyHttpContainerProvider.java

License:Open Source License

/**
 * Create and start Netty HTTP/2 server.
 * <p>/*from w w  w .  jav a2s.c om*/
 * The server is capable of connection upgrade to HTTP/2. HTTP/1.x request will be server as they were used to.
 * <p>
 * Note that this implementation cannot be more experimental. Any contributions / feedback is welcomed.
 *
 * @param baseUri       base uri.
 * @param configuration Jersey configuration.
 * @param sslContext    Netty {@link SslContext}.
 * @return Netty channel instance.
 * @throws ProcessingException when there is an issue with creating new container.
 */
public static Channel createHttp2Server(final URI baseUri, final ResourceConfig configuration,
        SslContext sslContext) throws ProcessingException {

    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    final NettyHttpContainer container = new NettyHttpContainer(configuration);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new JerseyServerInitializer(baseUri, sslContext, container, true));

        int port = getPort(baseUri);

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

        ch.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                container.getApplicationHandler().onShutdown(container);

                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        });

        return ch;

    } catch (InterruptedException e) {
        throw new ProcessingException(e);
    }
}

From source file:org.glowroot.agent.plugin.netty.Http2Server.java

License:Apache License

Http2Server(int port, boolean supportHttp1) throws InterruptedException {
    group = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_BACKLOG, 1024);
    b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(/*from  w w  w  .  jav a2s . c  om*/
                    supportHttp1 ? new Http2ServerWithHttp1SupportInitializer() : new Http2ServerInitializer());
    channel = b.bind(port).sync().channel();
}

From source file:org.greencheek.caching.herdcache.memcached.elasticacheconfig.server.StringServer.java

License:Apache License

/**
 * Override to set up your specific external resource.
 *
 * @throws if setup fails (which will disable {@code after}
 *///from   ww  w .j  a v  a2s .c  o  m
public void before(final String[] message, final TimeUnit delayUnit, final long delay,
        boolean sendAllMessages) {
    final ServerSocket socket = findFreePort();

    final ChannelHandler sharedHandler = new StringBasedServerHandler(message, delayUnit, delay,
            sendAllMessages);
    // do nothing
    try {
        final ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption.SO_SNDBUF, 100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        p.addLast(new ConfigGetClusterDecoder());
                        p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(sharedHandler);
                    }
                });

        // Start the server.
        if (startDelay > 0) {
            port = getPortNoClose(socket);
            workerGroup.schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        port = getPort(socket);
                        b.bind(port).sync();
                        outputStartedMessage();
                    } catch (InterruptedException e) {

                    }
                }
            }, startDelay, startDelayUnit);
        } else {
            port = getPort(socket);
            try {
                b.bind(port).sync();
                outputStartedMessage();
            } catch (InterruptedException e) {
            }
        }

    } finally {

    }
}

From source file:org.greencheek.dns.server.HttpHelloWorldServer.java

License:Apache License

public HttpHelloWorldServer(InetAddress address, int port) {
    // Configure the server.
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    try {//from   w  ww  .  ja  va2  s .  co m
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpHelloWorldServerInitializer(address));

        Channel ch = b.bind(address, port).sync().channel();

        System.err.println("Open your web browser and navigate to http" + "://" + address.getHostAddress() + ":"
                + port + '/');

    } catch (Exception e) {

    }

}

From source file:org.greencheek.elasticacheconfig.server.StringServer.java

License:Apache License

/**
 * Override to set up your specific external resource.
 *
 * @throws if setup fails (which will disable {@code after}
 *///  w w  w .  j a  v a 2s . c o m
public void before(final String[] message, final TimeUnit delayUnit, final long delay, boolean sendAllMessages)
        throws Throwable {
    final ServerSocket socket = findFreePort();

    final ChannelHandler sharedHandler = new StringBasedServerHandler(message, delayUnit, delay,
            sendAllMessages);
    // do nothing
    try {
        final ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption.SO_SNDBUF, 100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        p.addLast(new ConfigGetClusterDecoder());
                        p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(sharedHandler);
                    }
                });

        // Start the server.
        if (startDelay > 0) {
            port = getPortNoClose(socket);
            workerGroup.schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        port = getPort(socket);
                        b.bind(port).sync();
                        outputStartedMessage();
                    } catch (InterruptedException e) {

                    }
                }
            }, startDelay, startDelayUnit);
        } else {
            port = getPort(socket);
            b.bind(port).sync();
            outputStartedMessage();
        }

    } finally {

    }
}

From source file:org.hongxi.whatsmars.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/*w w  w.  j  a  va 2 s .  com*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = this.serverBootstrap
            .group(this.eventLoopGroupBoss, this.eventLoopGroupSelector)
            .channel(useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
            .childOption(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
            .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline()
                            .addLast(defaultEventExecutorGroup, HANDSHAKE_HANDLER_NAME,
                                    new HandshakeHandler(TlsSystemConfig.tlsMode))
                            .addLast(defaultEventExecutorGroup, new NettyEncoder(), new NettyDecoder(),
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()),
                                    new NettyConnectManageHandler(), new NettyServerHandler());
                }
            });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        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.nettyEventExecutor.start();
    }

    this.timer.scheduleAtFixedRate(new TimerTask() {

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

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

License:Apache License

public synchronized void start() throws Exception {
    if (channelClazz != null) {
        // Already started
        return;/*  w w  w.  j a va 2  s.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 HornetQThreadFactory("hornetq-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) {
                        HornetQServerLogger.LOGGER.invalidCipherSuite(SSLSupport
                                .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }

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

                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("hornetq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup = new DefaultChannelGroup("hornetq-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);
        }

        // TODO: Think about add Version back to netty
        HornetQServerLogger.LOGGER.startedNettyAcceptor(TransportConstants.NETTY_VERSION, host, port);
    }
}