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:com.friz.owari.network.server.Server.java

License:Open Source License

@Override
public void initialize() throws NoSuchAlgorithmException {
    bootstrap = new ServerBootstrap();

    bootstrap.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override//from www.j  av a 2  s  . c o  m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    pipeline.addLast(HandshakeDecoder.class.getName(), new HandshakeDecoder());
                    pipeline.addLast(HandshakeEncoder.class.getName(), new HandshakeEncoder());
                    pipeline.addLast(IdleStateHandler.class.getName(), new IdleStateHandler(15, 0, 0));
                    pipeline.addLast(ServerChannelHandler.class.getName(),
                            new ServerChannelHandler(Server.this));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    hub.listen(HandshakeEvent.class, new HandshakeListener());
    hub.listen(ExchangeRecieveEvent.class, new ExchangeListener());

    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DH");
    keyPairGenerator.initialize(1024);

    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    privateKey = keyPair.getPrivate();
    publicKey = keyPair.getPublic();
}

From source file:com.friz.update.UpdateServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    UpdateServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override/* w w w  .j  a va  2  s.  com*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(UpdateInitEncoder.class.getName(), new UpdateInitEncoder());
                    p.addLast(UpdateInitDecoder.class.getName(), new UpdateInitDecoder());
                    p.addLast(IdleStateHandler.class.getName(), new IdleStateHandler(15, 0, 0));
                    p.addLast(UpdateChannelHandler.class.getName(), new UpdateChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    hub.listen(UpdateRequestEvent.class, new UpdateRequestEventListener());
    hub.listen(XorRequestEvent.class, new XorRequestEventListener());
    hub.listen(FileRequestEvent.class, new FileRequestEventListener());

    service.startAsync();
}

From source file:com.gdut.Netty_testing.time_server.server.TimeServer.java

License:Apache License

/**
 * /*from   w  ww.j a v a  2s .  c  om*/
 * @Title: main
 * @Description: TODO
 * @param @param args
 * @param @throws Exception
 * @return void
 * @throws
 */
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        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.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), new TimeEncoder(),
                                new TimeServerHandler());
                        // new TimeEncoder(),
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();
        f.addListener(new GenericFutureListener<Future<? super Void>>() {

            public void operationComplete(Future<? super Void> future) throws Exception {
                // TODO Auto-generated method stub
                System.out.println("success " + future.isSuccess());
            }
        });

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

From source file:com.github.ambry.rest.NettyServer.java

License:Open Source License

@Override
public void start() throws InstantiationException {
    long startupBeginTime = System.currentTimeMillis();
    try {/*from  w  w  w.  j a  v  a  2 s  .c o  m*/
        logger.trace("Starting NettyServer deployment");
        ServerBootstrap b = new ServerBootstrap();
        // Netty creates a new instance of every class in the pipeline for every connection
        // i.e. if there are a 1000 active connections there will be a 1000 NettyMessageProcessor instances.
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, nettyConfig.nettyServerSoBacklog)
                .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(channelInitializer);
        b.bind(nettyConfig.nettyServerPort).sync();
        logger.info("NettyServer now listening on port {}", nettyConfig.nettyServerPort);
    } catch (InterruptedException e) {
        logger.error("NettyServer start await was interrupted", e);
        nettyMetrics.nettyServerStartError.inc();
        throw new InstantiationException(
                "Netty server bind to port [" + nettyConfig.nettyServerPort + "] was interrupted");
    } finally {
        long startupTime = System.currentTimeMillis() - startupBeginTime;
        logger.info("NettyServer start took {} ms", startupTime);
        nettyMetrics.nettyServerStartTimeInMs.update(startupTime);
    }
}

From source file:com.github.herong.rpc.netty.protobuf.demo1.ProtobufServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*w  w  w .j ava2s. c o  m*/
        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 {
                        ch.pipeline()
                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(AddressBookProtos.AddressBook.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new ProtobufServerHandler());
                    }
                });

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

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

From source file:com.github.herong.rpc.netty.protobuf.demo2.Demo2ProtobufServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w w  w  . j  av  a2s  .  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 ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(Message.DTO.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new Demo2ProtobufServerHandler());
                    }
                });

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

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

From source file:com.github.liyp.netty.App.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {//from   w ww . ja v  a  2  s.c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ReplayingDecoder() {
                            @Override
                            protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
                                    throws Exception {
                                short magicHeader = in.readShort();
                                logger.debug("Receive magic header: {}.", magicHeader);
                                if (magicHeader != HEADER) {
                                    logger.error("Receive illegal magic header: {}, close channel: {}.",
                                            magicHeader, ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                short dataLen = in.readShort();
                                logger.debug("Receive message data length: {}.", dataLen);
                                if (dataLen < 0) {
                                    logger.error("Data length is negative, close channel: {}.",
                                            ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                ByteBuf payload = in.readBytes(dataLen);
                                String cloudMsg = payload.toString(CharsetUtil.UTF_8);
                                logger.debug("Receive data: {}.", cloudMsg);
                                out.add(cloudMsg);
                            }
                        }).addLast(new MessageToByteEncoder<String>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out)
                                    throws Exception {
                                out.writeBytes(msg.getBytes());
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("start receive msg...");
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                logger.info("receive msg: {}", msg);
                                logger.info("echo msg");
                                ctx.writeAndFlush(msg);
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("9999");
        f.channel().closeFuture().sync();
    } finally {
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }
}

From source file:com.github.liyp.netty.HandlerChainApp.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {/*w w  w.  j  a v a  2 s . c  o  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("1");
                                ctx.fireChannelActive();
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("2");
                                ctx.fireChannelActive();
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("3");
                                ctx.fireChannelActive();
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("9999");
        f.channel().closeFuture().sync();
    } finally {
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }
}

From source file:com.github.sparkfy.network.server.TransportServer.java

License:Apache License

private void init(String hostToBind, int portToBind) {

    IOMode ioMode = IOMode.valueOf(conf.ioMode());
    EventLoopGroup bossGroup = NettyUtils.createEventLoop(ioMode, conf.serverThreads(), "shuffle-server");
    EventLoopGroup workerGroup = bossGroup;

    PooledByteBufAllocator allocator = NettyUtils.createPooledByteBufAllocator(conf.preferDirectBufs(),
            true /* allowCache */, conf.serverThreads());

    bootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
            .channel(NettyUtils.getServerChannelClass(ioMode)).option(ChannelOption.ALLOCATOR, allocator)
            .childOption(ChannelOption.ALLOCATOR, allocator);

    if (conf.backLog() > 0) {
        bootstrap.option(ChannelOption.SO_BACKLOG, conf.backLog());
    }//w w  w  . j a  v  a 2 s .  co m

    if (conf.receiveBuf() > 0) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, conf.receiveBuf());
    }

    if (conf.sendBuf() > 0) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, conf.sendBuf());
    }

    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            RpcHandler rpcHandler = appRpcHandler;
            for (TransportServerBootstrap bootstrap : bootstraps) {
                rpcHandler = bootstrap.doBootstrap(ch, rpcHandler);
            }
            context.initializePipeline(ch, rpcHandler);
        }
    });

    InetSocketAddress address = hostToBind == null ? new InetSocketAddress(portToBind)
            : new InetSocketAddress(hostToBind, portToBind);
    channelFuture = bootstrap.bind(address);
    channelFuture.syncUninterruptibly();

    port = ((InetSocketAddress) channelFuture.channel().localAddress()).getPort();
    logger.debug("Shuffle server started on port :" + port);
}

From source file:com.github.thinker0.mesos.MesosHealthCheckerServer.java

License:Apache License

/**
 * Initializes the server, socket, and channel.
 *
 * @param loopGroup          The event loop group.
 * @param serverChannelClass The socket channel class.
 * @throws InterruptedException on interruption.
 */// w w  w  .  j a  v  a2  s  . co  m
private void start(final EventLoopGroup loopGroup, final Class<? extends ServerChannel> serverChannelClass)
        throws InterruptedException {

    try {
        final InetSocketAddress inet = new InetSocketAddress(port);

        final ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.option(ChannelOption.SO_REUSEADDR, true);
        b.option(ChannelOption.SO_LINGER, 0);
        b.group(loopGroup).channel(serverChannelClass).childHandler(new WebServerInitializer());
        b.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        b.childOption(ChannelOption.SO_REUSEADDR, true);

        // final Channel ch = b.bind(inet).sync().channel();
        // ch.closeFuture().sync();
        b.bind(inet);
        logger.info("Listening for Admin on {}", inet);
    } catch (Throwable t) {
        logger.warn(t.getMessage(), t);
    } finally {
        // loopGroup.shutdownGracefully().sync();
    }
}