Example usage for io.netty.channel ChannelOption SO_KEEPALIVE

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

Introduction

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

Prototype

ChannelOption SO_KEEPALIVE

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

Click Source Link

Usage

From source file:NettyHttpListner.java

License:Apache License

public void start() {

    System.out.println("Starting the server...");
    System.out.println("Starting Inbound Http Listner on Port " + this.port);

    // Configure SSL.
    SslContext sslCtx = null;//from   w w w  .  j av a  2  s .  c  o m
    if (SSL) {
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (CertificateException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SSLException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    commonEventLoopGroup = new NioEventLoopGroup(bossGroupSize);
    //        bossGroup = new NioEventLoopGroup(bossGroupSize);
    //        workerGroup = new NioEventLoopGroup(workerGroupSize);

    try {
        ServerBootstrap b = new ServerBootstrap();

        //            b.commonEventLoopGroup(bossGroup, workerGroup)
        b.group(commonEventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(
                        new NettyHttpTransportHandlerInitializer(HOST, HOST_PORT, maxConnectionsQueued, sslCtx))
                .childOption(ChannelOption.AUTO_READ, false);

        b.option(ChannelOption.TCP_NODELAY, true);
        b.childOption(ChannelOption.TCP_NODELAY, true);

        b.option(ChannelOption.SO_BACKLOG, maxConnectionsQueued);

        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

        b.option(ChannelOption.SO_SNDBUF, 1048576);
        b.option(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_SNDBUF, 1048576);

        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        Channel ch = null;
        try {
            ch = b.bind(port).sync().channel();
            ch.closeFuture().sync();
            System.out.println("Inbound Listner Started");
        } catch (InterruptedException e) {
            System.out.println("Exception caught");
        }
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:HttpRouterServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    Router<String> router = new Router<String>().GET(PUBLIC_DIR + ":id", "public").GET("/", "index")
            .GET(PUBLIC_DIR, "index")
            //            .GET("/image", "base64")
            //            .GET("/img", "image")
            //            .GET("/",             "Index page")
            //            .GET("/articles/:id", "Article show page")
            .notFound("404 Not Found");
    System.out.println(router);/*ww  w. ja  va2 s .c  o  m*/

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

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE)
                .channel(NioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router));

        Channel ch = b.bind(PORT).sync().channel();
        System.out.println("Server started: http://127.0.0.1:" + PORT + '/');

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

From source file:Http2Client.java

License:Apache License

public Http2Client(final String host, final int port, final boolean ssl) throws Exception {
    this.host = host;
    this.port = port;
    this.ssl = ssl;

    // Configure SSL.
    if (ssl) {/*ww  w. ja v a  2 s .  c  o  m*/
        this.sslCtx = SslContext.newClientContext(null, InsecureTrustManagerFactory.INSTANCE, null,
                Arrays.asList(SelectedProtocol.HTTP_2.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()),
                0, 0);
    } else {
        this.sslCtx = null;
    }

    // XXX (dano): Http2Connection does not seem to be thread safe, use one thread only
    this.workerGroup = new NioEventLoopGroup(1);
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx);

    // Configure the client.
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.remoteAddress(host, port);
    b.handler(initializer);

    // Start the client.
    this.channel = b.connect().syncUninterruptibly().channel();
    System.out.println("Connected to [" + host + ':' + port + ']');

    // Wait for the HTTP/2 upgrade to occur.
    this.connectionHandler = initializer.connectionHandler();
    connectionHandler.awaitInitialization();
}

From source file:TestTCPServer.java

License:Open Source License

public static void main(String... args) throws Throwable {
    IOService service = new IOService();
    TCPAcceptor acceptor = new TCPAcceptor(service);
    acceptor.setOption(ChannelOption.SO_BACKLOG, 3);
    acceptor.setChildOption(ChannelOption.TCP_NODELAY, true);
    acceptor.setChildOption(ChannelOption.SO_KEEPALIVE, true);

    acceptor.bind(4321);/*from   w w  w.j a  va2s  .  c  o m*/
    TCPSocket con = acceptor.accept();
    ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(16 * 1000);
    byte[] bytea = new byte[buffer.capacity()];
    long bytes;

    System.out.println("Connected " + con.remoteEndpoint());
    bytes = con.receive(buffer);
    while (bytes != -1 && buffer.getByte(0) != 4) {
        buffer.readBytes(bytea, 0, (int) bytes);
        System.out.print(new String(bytea, 0, (int) bytes));
        buffer.readerIndex(0).writerIndex(0);
        con.send(buffer, (int) bytes);
        buffer.readerIndex(0).writerIndex(0);
        bytes = con.receive(buffer);
    }

    System.out.println("Connection closed");
    con.close();

    acceptor.close();
    service.cancel();
}

From source file:alluxio.client.netty.NettyClient.java

License:Apache License

/**
 * Creates and returns a new Netty client bootstrap for clients to connect to remote servers.
 *
 * @param handler the handler that should be added to new channel pipelines
 * @return the new client {@link Bootstrap}
 *///from w w w. ja  va 2 s.c  om
public static Bootstrap createClientBootstrap(final ClientHandler handler) {
    final Bootstrap boot = new Bootstrap();

    boot.group(WORKER_GROUP).channel(CLIENT_CHANNEL_CLASS);
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.option(ChannelOption.TCP_NODELAY, true);
    boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    boot.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast(RPCMessage.createFrameDecoder());
            pipeline.addLast(ENCODER);
            pipeline.addLast(DECODER);
            pipeline.addLast(handler);
        }
    });

    return boot;
}

From source file:alluxio.network.netty.NettyClient.java

License:Apache License

/**
 * Creates and returns a new Netty client bootstrap for clients to connect to remote servers.
 *
 * @param address the socket address//from   www  .j  a v  a  2  s  .  co m
 * @return the new client {@link Bootstrap}
 */
public static Bootstrap createClientBootstrap(SocketAddress address) {
    final Bootstrap boot = new Bootstrap();

    boot.group(WORKER_GROUP).channel(
            NettyUtils.getClientChannelClass(NettyUtils.CHANNEL_TYPE, !(address instanceof InetSocketAddress)));
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.option(ChannelOption.TCP_NODELAY, true);
    boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    if (NettyUtils.CHANNEL_TYPE == ChannelType.EPOLL) {
        boot.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    }

    // After 10 missed heartbeat attempts and no write activity, the server will close the channel.
    final long timeoutMs = Configuration.getMs(PropertyKey.NETWORK_NETTY_HEARTBEAT_TIMEOUT_MS);
    final long heartbeatPeriodMs = Math.max(timeoutMs / 10, 1);
    boot.handler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast(RPCMessage.createFrameDecoder());
            pipeline.addLast(ENCODER);
            pipeline.addLast(DECODER);
            pipeline.addLast(new IdleStateHandler(0, heartbeatPeriodMs, 0, TimeUnit.MILLISECONDS));
            pipeline.addLast(new IdleWriteHandler());
        }
    });

    return boot;
}

From source file:at.yawk.accordion.netty.NettyConnector.java

License:Mozilla Public License

@Override
public Optional<Connection> connect(SocketAddress address) {
    // TODO find a non-hacky method to close channels
    Collection<Channel> registeredChannels = Collections.synchronizedList(new ArrayList<>());

    EventLoopGroup workerGroup = new NioEventLoopGroup() {
        @Override/*  w ww.  j av a 2s .  com*/
        public ChannelFuture register(Channel channel, ChannelPromise promise) {
            registeredChannels.add(channel);
            return super.register(channel, promise);
        }
    };

    AtomicReference<Connection> connectionRef = new AtomicReference<>();

    // init
    Bootstrap bootstrap = new Bootstrap().group(workerGroup).handler(new ChannelHandlerAdapter() {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            NettyConnection connection = new NettyConnection(ctx.channel());
            connectionRef.set(connection);
            connection.init();
        }
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true);

    try {
        // connect
        ChannelFuture connectFuture = bootstrap.connect(address);
        // wait for connection
        connectFuture.sync();
        return Optional.of(connectionRef.get());
    } catch (Exception e) {
        // shut down workers
        workerGroup.shutdownGracefully();

        // kill channels
        registeredChannels.forEach(NettyConnection::close);

        return Optional.empty();
    }
}

From source file:at.yawk.accordion.netty.NettyConnector.java

License:Mozilla Public License

@Override
public Server listen(SocketAddress inf) {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, BACKLOG_VALUE).childOption(ChannelOption.SO_KEEPALIVE, true);

    NettyServer server = new NettyServer(bootstrap, inf);
    server.init();/* ww w  .  ja v a 2 s .co m*/

    return server;
}

From source file:at.yawk.votifier.VotifierServerImpl.java

License:Mozilla Public License

public void init() {
    if (!initialized.compareAndSet(false, true)) {
        return;/*from w  w w  .j ava  2s.  c o  m*/
    }

    logger.info("Initializing votifier server...");
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
                    logger.fine("Client disconnected.");
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    handleError(cause);
                }

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new VoteDecrypter(key)).addLast(new LineSplitter())
                            .addLast(new VoteDecoder()).addLast(new VersionEncoder())
                            .addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg)
                                        throws Exception {
                                    if (!(msg instanceof Operation)) {
                                        return;
                                    }
                                    Operation operation = (Operation) msg;
                                    if (operation.getOperation().equals("VOTE")) {
                                        listener.accept(
                                                new VoteEvent(operation.getUsername(), operation.getService(),
                                                        operation.getAddress(), operation.getTimestamp()));
                                        ctx.channel().close();
                                    } else {
                                        throw new UnsupportedOperationException(operation.getOperation());
                                    }
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                        throws Exception {
                                    handleError(cause);
                                }
                            });

                    logger.info("Client connected: Sending version packet.");
                    ch.writeAndFlush(version);
                }
            });
}

From source file:be.yildizgames.module.network.netty.server.ServerNetty.java

License:MIT License

/**
 * Create a new Netty server.// w  w  w.ja v a  2  s.  c o  m
 *
 */
//@requires bootstrap != null.
//@requires port > 0 < 65535.
private ServerNetty() {
    super();

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    this.bootstrap = new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
    this.bootstrap.option(ChannelOption.TCP_NODELAY, true);
    this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
}