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:example.http.helloworld.HttpHelloWorldServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {// w  w w . jav a  2s  . c  om
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } 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 HttpHelloWorldServerInitializer(sslCtx));

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

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

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

From source file:example.http2.helloworld.frame.server.Http2Server.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//  w  w w. ja  va  2s  .c o m
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }
    // Configure the server.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new Http2ServerInitializer(sslCtx));

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

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

        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:favoorr.netty.protocol.netty.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO//w w  w.  j  ava  2  s  .  c  om
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws IOException {
                    ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));
                    ch.pipeline().addLast(new NettyMessageEncoder());
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                    ch.pipeline().addLast(new LoginAuthRespHandler());
                    ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());
                }
            });

    // ???
    ChannelFuture f = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();

    System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));

    f.channel().closeFuture().sync();
}

From source file:fr.kissy.zergling_push.MainServer.java

License:Apache License

private void run() throws Exception {
    final ChannelGroup allPlayers = new DefaultChannelGroup("AllPlayers", GlobalEventExecutor.INSTANCE);
    final ArrayBlockingQueue<PlayerMessage> messagesQueue = new ArrayBlockingQueue<PlayerMessage>(1024);

    final World world = new World();
    final MainLoop mainLoop = new MainLoop(world, allPlayers, messagesQueue);

    ScheduledThreadPoolExecutor mainLoopExecutor = new ScheduledThreadPoolExecutor(1);
    mainLoopExecutor.scheduleAtFixedRate(mainLoop, 0, TICK_RATE, TimeUnit.MILLISECONDS);

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(16);

    try {//from   w  ww.j  ava 2s  . c  o  m
        final ServerBootstrap sb = new ServerBootstrap();
        sb.childOption(ChannelOption.TCP_NODELAY, true);
        sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("http-decoder", new HttpServerCodec());
                        pipeline.addLast("http-aggregator", new HttpObjectAggregator(65536));
                        pipeline.addLast("websocket-compression", new WebSocketServerCompressionHandler());
                        pipeline.addLast("websocket-protocol",
                                new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true));
                        pipeline.addLast(executorGroup, "flatbuffer-message",
                                new FlatBufferMessageHandler(world, messagesQueue));
                        pipeline.addLast("http-server", new HttpStaticFileServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        final Channel ch = sb.bind(8080).sync().channel();
        ch.closeFuture().sync();
    } catch (Exception e) {
        throw new RuntimeException("Error while running server", e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:fr.letroll.ttorrentandroid.client.io.PeerServer.java

License:Apache License

public void start() throws Exception {
    group = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(group);/*ww  w .  j a  v a  2s.  co  m*/
    b.channel(NioServerSocketChannel.class);
    b.option(ChannelOption.SO_BACKLOG, 128);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.childHandler(new PeerServerHandshakeHandler(client));
    b.childOption(ChannelOption.SO_KEEPALIVE, true);
    // b.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES));
    if (address != null) {
        future = b.bind(address).sync();
    } else {
        BIND: {
            Exception x = new IOException("No available port for the BitTorrent client!");
            for (int i = PORT_RANGE_START; i <= PORT_RANGE_END; i++) {
                try {
                    future = b.bind(i).sync();
                    break BIND;
                } catch (InterruptedException e) {
                    throw e;
                } catch (Exception e) {
                    x = e;
                }
            }
            throw new IOException("Failed to find an address to bind in range [" + PORT_RANGE_START + ","
                    + PORT_RANGE_END + "]", x);
        }
    }
}

From source file:godfinger.http.HttpServer.java

License:Apache License

public HttpServer(int port, HttpRequestProcessor requestProcessor) {
    this.port = port;
    bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
    bootstrap.group(bossGroup, workerGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.handler(new LoggingHandler(LogLevel.INFO));
    bootstrap.childHandler(new HttpServerInitializer(requestProcessor));
}

From source file:herddb.network.netty.NettyChannelAcceptor.java

License:Apache License

public void start() throws Exception {
    if (ssl) {//from   www .ja  v  a2  s .  c  o  m
        if (sslCertFile == null) {
            LOGGER.log(Level.SEVERE, "start SSL with self-signed auto-generated certificate");
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            try {
                sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).ciphers(sslCiphers)
                        .build();
            } finally {
                ssc.delete();
            }
        } else {
            LOGGER.log(Level.SEVERE, "start SSL with certificate " + sslCertFile.getAbsolutePath()
                    + " chain file " + sslCertChainFile.getAbsolutePath());
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            sslCtx = SslContextBuilder.forServer(sslCertChainFile, sslCertFile, sslCertPassword)
                    .ciphers(sslCiphers).build();
        }

    }

    if (callbackThreads == 0) {
        callbackExecutorQueue = new SynchronousQueue<Runnable>();
        callbackExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
                callbackExecutorQueue, threadFactory);
    } else {
        callbackExecutorQueue = new LinkedBlockingQueue<Runnable>();
        callbackExecutor = new ThreadPoolExecutor(callbackThreads, callbackThreads, 0L, TimeUnit.MILLISECONDS,
                callbackExecutorQueue, threadFactory);
    }
    statsLogger.registerGauge("callbacksqueue", new Gauge<Integer>() {
        @Override
        public Integer getDefaultValue() {
            return 0;
        }

        @Override
        public Integer getSample() {
            return callbackExecutorQueue.size();
        }

    });
    InetSocketAddress address = new InetSocketAddress(host, port);
    LOGGER.log(Level.SEVERE, "Starting HerdDB network server at {0}:{1}", new Object[] { host, port + "" });
    if (address.isUnresolved()) {
        throw new IOException("Bind address " + host + ":" + port + " cannot be resolved");
    }
    ChannelInitializer<io.netty.channel.Channel> channelInitialized = new ChannelInitializer<io.netty.channel.Channel>() {
        @Override
        public void initChannel(io.netty.channel.Channel ch) throws Exception {
            NettyChannel session = new NettyChannel("unnamed", ch, callbackExecutor);
            if (acceptor != null) {
                acceptor.createConnection(session);
            }

            //                        ch.pipeline().addLast(new LoggingHandler());
            // Add SSL handler first to encrypt and decrypt everything.
            if (ssl) {
                ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));
            }

            ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
            ch.pipeline().addLast("lengthbaseddecoder",
                    new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            //                
            ch.pipeline().addLast("messagedecoder", new ProtocolMessageDecoder());
            ch.pipeline().addLast(new ServerInboundMessageHandler(session));
        }
    };
    if (enableRealNetwork) {
        if (NetworkUtils.isEnableEpoolNative()) {
            bossGroup = new EpollEventLoopGroup(workerThreads);
            workerGroup = new EpollEventLoopGroup(workerThreads);
            LOGGER.log(Level.FINE, "Using netty-native-epoll network type");
        } else {
            bossGroup = new NioEventLoopGroup(workerThreads);
            workerGroup = new NioEventLoopGroup(workerThreads);
            LOGGER.log(Level.FINE, "Using nio network type");
        }

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NetworkUtils.isEnableEpoolNative() ? EpollServerSocketChannel.class
                        : NioServerSocketChannel.class)
                .childHandler(channelInitialized).option(ChannelOption.SO_BACKLOG, 128);
        ChannelFuture f = b.bind(address).sync();
        this.channel = f.channel();

    }

    if (enableJVMNetwork) {
        localBossGroup = new DefaultEventLoopGroup(workerThreads);
        localWorkerGroup = new DefaultEventLoopGroup(workerThreads);
        ServerBootstrap b_local = new ServerBootstrap();
        b_local.group(localBossGroup, localWorkerGroup).channel(LocalServerChannel.class)
                .childHandler(channelInitialized);

        String hostAddress = NetworkUtils.getAddress(address);
        LocalServerRegistry.registerLocalServer(hostAddress, port, ssl);

        ChannelFuture local_f = b_local.bind(new LocalAddress(hostAddress + ":" + port + ":" + ssl)).sync();
        this.local_channel = local_f.channel();
    }

}

From source file:http2.server.Http2Server.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.setProperty("jsse.enableSNIExtension", "true");

    // Configure SSL.
    try {/*from w ww.j  a  v  a  2  s  .  c o m*/
        String password = "http2";
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(null);
        ks.setKeyEntry("alias", ((KeyPair) getPem(Config.getString("privateKey"))).getPrivate(),
                password.toCharArray(), new java.security.cert.Certificate[] {
                        (X509Certificate) getPem(Config.getString("certificate")) });

        kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, password.toCharArray());
    } catch (Exception e) {
        logger.error("transfer from pem file to pkcs12 failed!", e);
    }

    final SslContext sslCtx;
    if (SSL) {
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;

        sslCtx = SslContextBuilder.forServer(kmf).sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup group = new NioEventLoopGroup();
    try

    {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new Http2ServerInitializer(sslCtx));

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

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

        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:httprestfulserver.HttpRESTfulServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from w ww  . j  ava2 s  . co m
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } 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 HttpRESTfulServerInitializer(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:hws.channel.net.NetDeliver.java

License:Apache License

public void start() {
    super.start();

    try {//from w w  w.jav a  2 s  . c  o m
        out = new PrintWriter(new BufferedWriter(
                new FileWriter("/home/hadoop/rcor/yarn/channel-deliver-" + channelName() + ".out")));
        out.println("Starting channel deliver: " + channelName() + " instance " + instanceId());
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (Exception e) {
            out.println("ERROR: " + e.getMessage());
            out.flush();
        }
    } else {
        sslCtx = null;
    }

    final ChannelDeliver deliverHandler = this;
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        //p.addLast(new EchoServerHandler());
                        p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                        p.addLast(new DefaultEventExecutorGroup(2), new NetDeliverHandler(deliverHandler));
                    }
                });

        out.println("Binding to a listening port");
        out.flush();
        // Start the server.
        ChannelFuture f = b.bind(0).sync();
        this.serverChannel = f.channel();
        this.latch = new CountDownLatch(1);

        SocketAddress socketAddress = this.serverChannel.localAddress();
        if (socketAddress instanceof InetSocketAddress) {
            out.println("Connected to port: " + ((InetSocketAddress) socketAddress).getPort());
            out.flush();
            shared().set("host-" + instanceId(), hws.net.NetUtil.getLocalCanonicalHostName());
            shared().set("port-" + instanceId(), new Integer(((InetSocketAddress) socketAddress).getPort()));
        }
        out.println("Host: " + hws.net.NetUtil.getLocalCanonicalHostName());
        out.println("Connected to: " + f.channel().localAddress().toString());
        out.flush();

        out.println("Running server, waiting for a close command");
        out.flush();
        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
        out.println("Channel closed");
        out.flush();
    } catch (Exception e) {
        out.println("ERROR: " + e.getMessage());
        out.flush();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
    out.println("Counting down the latch");
    out.flush();
    this.latch.countDown();
}