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.shelloid.vpt.agent.LocalLink.java

License:Open Source License

public Channel bind(int port) throws Exception {
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 20)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   w  w  w  . jav  a 2 s .  c  om*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new AppSideAgentHandler());
                }
            });
    ChannelFuture f = b.bind(port).sync();
    final Channel ch = f.channel();
    if (f.isSuccess()) {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                long timeOut = 1000 * 60 * 5;
                Platform.shelloidLogger.info("Gracefull shutdown initiated.");
                ChannelFuture cf = ch.close();
                cf.awaitUninterruptibly(timeOut);
                bossGroup.shutdownGracefully().awaitUninterruptibly(timeOut);
                workerGroup.shutdownGracefully().awaitUninterruptibly(timeOut);
                Platform.shelloidLogger.info("Gracefull shutdown finidhed.");
            }
        });
        return ch;
    } else {
        throw new Exception("Can't bind to " + port);
    }
}

From source file:org.skfiy.typhon.net.Netty4Connector.java

License:Apache License

@Override
protected void startInternal() throws LifecycleException {
    setState(LifecycleState.STARTING);/* w w  w.  j  a  va  2s .  c o m*/
    fireLifecycleListener(START_EVENT);

    System.setProperty("io.netty.noJdkZlibDecoder", "false");

    final byte[] delimiters = new byte[] { '\n' };

    final String compressionMode = Typhons.getProperty("typhon.spi.net.compressionMode");
    final Netty4EndpointHandler handler = new Netty4EndpointHandler();
    final Netty4ConnectionLimitHandler limitHandler = new Netty4ConnectionLimitHandler();

    // ????
    final LengthFieldPrepender lengthFieldPrepender;
    final DelimiterBasedFrameEncoder delimiterBasedFrameEncoder;
    if ("zlib".equals(compressionMode)) {
        lengthFieldPrepender = new LengthFieldPrepender(4);
        delimiterBasedFrameEncoder = null;
    } else {
        lengthFieldPrepender = null;
        delimiterBasedFrameEncoder = new DelimiterBasedFrameEncoder(delimiters);
    }

    // 
    final LoggingHandler loggingHandler;
    if (isLogEnabled()) {
        loggingHandler = new LoggingHandler(LogLevel.DEBUG);
    } else {
        loggingHandler = null;
    }

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(new NioEventLoopGroup(1), new NioEventLoopGroup())
            .channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
            .childHandler(new ChannelInitializer() {

                @Override
                protected void initChannel(Channel c) throws Exception {
                    ChannelPipeline pipeline = c.pipeline();
                    if ("zlib".equals(compressionMode)) {
                        pipeline.addLast("lengthFieldPrepender", lengthFieldPrepender);
                        pipeline.addLast("lengthFieldBasedFrameDecoder",
                                new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                        pipeline.addLast("deflater", ZlibCodecFactory.newZlibEncoder(ZlibWrapper.ZLIB));
                    } else {
                        pipeline.addLast("delimiterBasedFrameDecoder", new DelimiterBasedFrameDecoder(65535,
                                new ByteBuf[] { Unpooled.wrappedBuffer(delimiters) }));
                        pipeline.addLast("delimiterBasedFrameEncoder", delimiterBasedFrameEncoder);
                    }

                    if (isLogEnabled()) {
                        pipeline.addLast(loggingHandler);
                    }

                    pipeline.addLast(new IdleStateHandler(60 * 10, 60 * 10, 0));
                    pipeline.addLast(limitHandler, handler);
                }
            });

    channel = serverBootstrap.bind(host, port).channel();
    CLOG.debug("Netty4Connector started on port {}", port);

    MBeanServer mbs = MBeanUtils.REGISTRY.getMBeanServer();
    Object obj = null;
    try {
        obj = mbs.invoke(Container.OBJECT_NAME, "getInstance", new Object[] { ProtocolHandler.class },
                new String[] { Class.class.getName() });
    } catch (Exception ex) {
        CLOG.error("ProtocolHandler", ex);
        throw new TyphonException(ex);
    }
    handler.setProtocolHandler((ProtocolHandler) obj);
}

From source file:org.spongepowered.clean.network.NetworkManager.java

License:MIT License

public void startListening(int port) {
    try {//from w w  w.j  a  v a 2 s  .c o  m
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        this.serverkeys = generator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        CoreScheduler.emergencyShutdown(e);
    }

    this.bossGroup = new NioEventLoopGroup();
    this.workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(this.bossGroup, this.workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("splitter", new PacketSplitter());
                    ch.pipeline().addLast("decoder", new PacketDecoder());
                    ch.pipeline().addLast("length_appender", new PacketLengthAppender());
                    ch.pipeline().addLast("encoder", new PacketEncoder());
                    NetworkConnection conn = new NetworkConnection();
                    NetworkManager.this.activeConnections.add(conn);
                    ch.pipeline().addLast("handler", new PacketHandler(conn));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    this.channel = b.bind(port).syncUninterruptibly();
    SGame.getLogger().info("Now listening on port " + port);
}

From source file:org.springframework.boot.context.embedded.netty.NettyEmbeddedServletContainer.java

License:Apache License

private void groups(ServerBootstrap b) {
    //comment the epoll codes, the epoll evn is hard to build
    /*  if (StandardSystemProperty.OS_NAME.value().equals("Linux")) {
    bossGroup = new EpollEventLoopGroup(1);
    workerGroup = new EpollEventLoopGroup();
    b.channel(EpollServerSocketChannel.class)
            .group(bossGroup, workerGroup)
            .option(EpollChannelOption.TCP_CORK, true);
      } else {//from   w w w  .  ja v a  2 s  .  co  m
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    b.channel(NioServerSocketChannel.class)
            .group(bossGroup, workerGroup);
      }*/
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    b.channel(NioServerSocketChannel.class).group(bossGroup, workerGroup);
    b.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_BACKLOG, 100);
    logger.info("Bootstrap configuration: " + b.toString());
}

From source file:org.starnub.starnubserver.servers.starbound.TCPProxyServer.java

License:Open Source License

public void start() {
    ServerBootstrap starNubInbound_TCP_Socket = new ServerBootstrap();
    serverChannel = starNubInbound_TCP_Socket.group(connectionBossGroup, connectionWorkerGroup)
            .channel(channelClass).option(ChannelOption.SO_BACKLOG, serverBacklog)
            .childOption(ChannelOption.TCP_NODELAY, noDelay).childOption(ChannelOption.ALLOCATOR, socketBuffer)
            .childHandler(new TCPProxyServerInitializer(starboundAddress, starboundPort)).bind(starnubPort)
            .channel();/*from   www. j  ava2s . c o m*/
}

From source file:org.stem.net.Server.java

License:Apache License

public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100).childOption(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true).handler(new LoggingHandler(LogLevel.TRACE))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from   w  w  w.j a v  a  2  s. c o m
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new PacketDecoder()).addLast(new PacketEncoder())

                            .addLast(new MessageDecoder()).addLast(new MessageEncoder())

                            .addLast(new MessageDispatcher());
                }
            });

    try {
        future = bootstrap.bind(socket).sync();
        logger.info("Starting listening for clients on {}...", socket);
        channel = future.channel();

        // Wait until server socket is closed.
        // channel.closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
        throw new RuntimeException("Can't start server: ", e);
    }

}

From source file:org.telegram.server.TelegramServer.java

License:Open Source License

public void run() throws Exception {
    HazelcastConnection.getInstance();//w  w w  .ja v  a2 s  .com
    DatabaseConnection.getInstance();
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new MTProtoDecoder(), new MTProtoEncoder(),
                                new TelegramServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync();

        // 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.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:org.thingsplode.synapse.endpoint.Endpoint.java

License:Apache License

public Endpoint start() throws InterruptedException {
    try {//w ww. ja  v  a  2 s  .c o m
        logger.debug("Starting endpoint [" + endpointId + "].");

        this.initGroups();
        this.bootstrap.group(this.masterGroup, this.workerGroup);
        boolean ws = transportTypes.contains(Transport.WEBSOCKET);
        //if bidirectional communication is permitted /add more protocols here later
        bidirectionalCommsEnabled = ws;
        if (bidirectionalCommsEnabled) {
            if (this.messageStore == null) {
                this.messageStore = new MsgIdRspCorrelator();
            }
            if (this.msgIdGeneratorStrategy == null) {
                this.msgIdGeneratorStrategy = () -> UUID.randomUUID().toString();
            }
        }
        if (transportTypes.contains(Transport.HTTP) || ws) {
            this.bootstrap.channel(NioServerSocketChannel.class).childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(HTTP_ENCODER, new HttpResponseEncoder());
                            p.addLast(HTTP_DECODER, new HttpRequestDecoder());
                            p.addLast(HTTP_AGGREGATOR, new HttpObjectAggregator(1048576));
                            if (introspection) {
                                p.addLast(RESPONSE_INTROSPECTOR, new ResponseIntrospector());
                                p.addLast(HTTP_REQUEST_INTROSPECTOR, new HttpRequestIntrospector());
                            }
                            p.addLast(HTTP_REQUEST_HANDLER, new HttpRequestHandler(endpointId, pipelining));
                            //p.addLast(evtExecutorGroup, HTTP_REQUEST_HANDLER, new HttpRequestHandler(endpointId, pipelining, websocketSupport));
                            p.addLast(REQUEST_HANDLER, new RequestHandler(serviceRegistry, channelRegistry));
                            if (fileHandler != null) {
                                p.addLast(evtExecutorGroup, HTTP_FILE_HANDLER, fileHandler);
                            }
                            //todo: add pipelining
                            //                                if (pipelining) {
                            //                                    p.addLast(RESPONSE_SEQUENCER, new ResponseSequencer());
                            //                                }
                            p.addLast(HTTP_RESPONSE_HANDLER, new HttpResponseHandler());
                            if (bidirectionalCommsEnabled) {
                                p.addLast(CMD_RESULT_HANDLER, new CommandResultHandler(messageStore));
                            }
                        }
                    });
        } else {
            this.bootstrap.channel(EpollServerDomainSocketChannel.class)
                    .childHandler(new ChannelInitializer<DomainSocketChannel>() {
                        @Override
                        protected void initChannel(DomainSocketChannel ch) throws Exception {
                            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                        }
                    });
        }
        this.bootstrap.handler(new LoggingHandler(logLevel)).option(ChannelOption.SO_BACKLOG, 3);
    } catch (Exception ex) {
        this.logger.error(Endpoint.class.getSimpleName() + " interrupted due to: " + ex.getMessage(), ex);
    } finally {
        this.logger.debug("Adding shutdown hook for the endpoint.");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            this.logger.info("Endpoint shutdown hook activated [{}].", endpointId);
            this.stop();
            ForkJoinPool.commonPool().awaitQuiescence(5, TimeUnit.SECONDS);
        }));
    }
    this.startInternal();
    return this;
}

From source file:org.tiger.netty.netty.demo1.TimeServer.java

License:Apache License

public void bind(int port) throws Exception {
    //NioEventLoopGroup?NIO?Reactor
    //??SocketChannel
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {// www.  jav a2  s. com
        //ServerBootstrapNetty?NIO???????
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler());//Handler??IO
        // ???
        ChannelFuture f = b.bind(port).sync();
        System.out.println(" started and listen on " + f.channel().localAddress());
        // ???
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.tiger.netty.rpc.all.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    //??NIO/*w w w .j ava  2s . c  om*/
    //????EventLoopGroup
    //NioEventLoopGroupReactor
    //???boss?Reactor?
    //???worker??IOReactor?
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    //Netty??
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
            //Channel????????
            .channel(NioServerSocketChannel.class)
            //TCP?
            //backlog???
            //??TCP??
            //??listen?syn(connect)??
            //????syn???(?synack)
            // ????????
            //accept???????
            //backlog5?Web??lighttpd128*8
            //???syn??
            //Nettybacklog100???
            .option(ChannelOption.SO_BACKLOG, 100)
            //?HandlerHandler???HandlerNioServerSocketChannelChannelPipelineHandler
            //HandlerSocketChannelChannelPipelineHandler
            .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 future = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();
    System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
    future.channel().closeFuture().sync();
}