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:lunarion.node.LunarDBServerStandAlone.java

License:Open Source License

public void bind(int port) throws InterruptedException {

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.RCVBUF_ALLOCATOR,
                    new AdaptiveRecvByteBufAllocator(64, 1024, 65536 * 512))
            .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new LunarDBServerChannelInitializer(node_tc));

    Channel ch = bootstrap.bind(port).sync().channel();
    System.err.println(Timer.currentTime() + " DB node server channel binded at port: " + port + '.');
    logger.info(Timer.currentTime() + " [NODE INFO]:  DB node server channel binded at port: " + port + '.');
    ch.closeFuture().sync();/*from w  w w  .  j  a  v  a2 s  . c o m*/
    /*
     *  Bind and start to accept incoming connections.
     */
    // ChannelFuture future = bootstrap.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.
     */

    // future.channel().closeFuture().sync();

}

From source file:lunarion.node.requester.LunarDBClient.java

License:Open Source License

public ChannelFuture connect(String host, int port) throws Exception {
    group = new NioEventLoopGroup();
    client_handler = new ClientHandler(internal);

    try {//from   ww  w  . j a v  a  2 s .  c  o m
        Bootstrap client_bootstrap = new Bootstrap();
        client_bootstrap.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.SO_SNDBUF, 1024 * 1024)
                .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 1024, 65536 * 512))
                //.option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true).handler(new ClientChannelInitializer(client_handler));

        //ChannelFuture cf = client_bootstrap.connect(host, port).sync();
        ChannelFuture cf = client_bootstrap.connect(host, port);
        channel_list.add(cf);

        cf.addListener(new ChannelFutureListener() {
            public void operationComplete(final ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    ClientHandler handler = channelFuture.channel().pipeline().get(ClientHandler.class);
                    client_handler = handler;

                }
            }
        });

        connected.set(true);
        connected_host_ip = host;
        connected_port = port;

        return cf;
    } finally {

        // group.shutdownGracefully();
    }
}

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

License:Apache License

public void start() throws Exception {
    boolean useOpenSSL = NetworkUtils.isOpenSslAvailable();
    if (ssl) {/*from ww  w.  ja va2s.  co  m*/

        if (sslCertFile == null) {
            LOGGER.log(Level.SEVERE,
                    "start SSL with self-signed auto-generated certificate, useOpenSSL:" + useOpenSSL);
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            try {
                sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
                        .sslProvider(useOpenSSL ? SslProvider.OPENSSL : SslProvider.JDK).ciphers(sslCiphers)
                        .build();
            } finally {
                ssc.delete();
            }
        } else {
            LOGGER.log(Level.SEVERE, "start SSL with certificate " + sslCertFile.getAbsolutePath()
                    + " chain file " + sslCertChainFile.getAbsolutePath() + " , useOpenSSL:" + useOpenSSL);
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            sslCtx = SslContextBuilder.forServer(sslCertChainFile, sslCertFile, sslCertPassword)
                    .sslProvider(useOpenSSL ? SslProvider.OPENSSL : SslProvider.JDK).ciphers(sslCiphers)
                    .build();
        }

    }
    if (NetworkUtils.isEnableEpollNative()) {
        bossGroup = new EpollEventLoopGroup(workerThreads);
        workerGroup = new EpollEventLoopGroup(workerThreads);
        LOGGER.log(Level.INFO, "Using netty-native-epoll network type");
    } else {
        bossGroup = new NioEventLoopGroup(workerThreads);
        workerGroup = new NioEventLoopGroup(workerThreads);
    }
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(
            NetworkUtils.isEnableEpollNative() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    NettyChannel session = new NettyChannel("client", ch, callbackExecutor, null);
                    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("messageencoder", new DodoMessageEncoder());
                    ch.pipeline().addLast("messagedecoder", new DodoMessageDecoder());
                    ch.pipeline().addLast(new InboundMessageHandler(session));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture f = b.bind(host, port).sync(); // (7)
    this.channel = f.channel();

}

From source file:me.ferrybig.p2pnetwork.Main.java

private void startIncomingConnectionThread(int port) {
    ServerBootstrap server = new ServerBootstrap();
    server.group(group);/*from  w w w  . j  a va  2 s.c o m*/
    server.channel(NioServerSocketChannel.class);
    server.option(ChannelOption.SO_BACKLOG, 128);
    server.childOption(ChannelOption.SO_KEEPALIVE, true);
    server.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            if (blocked.containsKey(((InetSocketAddress) ch.remoteAddress()).getAddress())) {
                LOG.info(ch + "Rejected at socket level");
                ch.close();
                return;
            }
            ch.pipeline().addLast(new LengthFieldPrepender(4));
            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            ch.pipeline().addLast(new PacketEncoder());
            ch.pipeline().addLast(new PacketDecoder());
            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            ch.pipeline().addLast(new ServerBootstrapConnector(addr, incomingListener));
            clientsIn.add(ch);
            ch.closeFuture().addListener(e1 -> {
                clientsIn.remove(ch);
            });
        }
    });
    ChannelFuture f = server.bind(port);
    f.addListener(e -> {
        this.servers.add((ServerChannel) f.channel());
        f.channel().closeFuture().addListener(e1 -> {
            this.servers.remove((ServerChannel) f.channel());
        });
    });
}

From source file:me.ferrybig.p2pnetwork.Main.java

private void startOutgomingConnectionThread(InetAddress address, int port) {
    Bootstrap client = new Bootstrap();
    client.group(group);//from  w w  w  .j  a  v a  2 s . c  o m
    client.channel(NioSocketChannel.class);
    client.option(ChannelOption.SO_KEEPALIVE, true);
    client.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new LengthFieldPrepender(4));
            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            ch.pipeline().addLast(new PacketEncoder());
            ch.pipeline().addLast(new PacketDecoder());
            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            ch.pipeline().addLast(new ServerBootstrapConnector(addr, outgoingListener));
        }
    });
    ChannelFuture f = client.connect(address, port);
    f.addListener(e -> {
        this.clientsOut.add(f.channel());
        f.channel().closeFuture().addListener(e1 -> {
            this.clientsOut.remove(f.channel());
        });
    });
}

From source file:me.ferrybig.p2pnetwork.Peer.java

public ChannelFuture startIncomingConnectionThread(int port) {
    ServerBootstrap server = new ServerBootstrap();
    server.group(group);//from w  w w .  ja v  a 2s . c o  m
    server.channel(NioServerSocketChannel.class);
    server.option(ChannelOption.SO_BACKLOG, 128);
    server.childOption(ChannelOption.SO_KEEPALIVE, true);
    server.childHandler(new ChannelConstructor(incomingListener, clientsIn));
    ChannelFuture f = server.bind(port);
    return f.addListener(e -> {
        if (e.isSuccess()) {
            this.servers.add((ServerChannel) f.channel());
            f.channel().closeFuture().addListener(e1 -> {
                this.servers.remove((ServerChannel) f.channel());
            });
        }
    });
}

From source file:me.ferrybig.p2pnetwork.Peer.java

public ChannelFuture startOutgomingConnectionThread(InetAddress address, int port) {
    Bootstrap client = new Bootstrap();
    client.group(group);//  www  .  jav  a2  s  .c  om
    client.channel(NioSocketChannel.class);
    client.option(ChannelOption.SO_KEEPALIVE, true);
    client.handler(new ChannelConstructor(outgoingListener, clientsOut));
    ChannelFuture f = client.connect(address, port);
    return f.addListener(e -> {
        this.clientsOut.add(f.channel());
        f.channel().closeFuture().addListener(e1 -> {
            this.clientsOut.remove(f.channel());
        });
    });
}

From source file:me.jtalk.socketconnector.io.TCPManager.java

License:Open Source License

private ServerBootstrap instantiateServer(TCPActivationSpec spec) throws ResourceException {

    ServerBootstrap newServer = new ServerBootstrap();
    newServer.group(this.listeners, this.workers);
    newServer.channel(NioServerSocketChannel.class);
    newServer.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override//from  w  w  w.  j  ava 2s . c o m
        protected void initChannel(SocketChannel c) throws Exception {
            c.pipeline().addLast(new Receiver(TCPManager.this, TCPManager.this.ids.incrementAndGet()))
                    .addLast(new Sender());
        }
    });
    newServer.option(ChannelOption.SO_KEEPALIVE, true);
    newServer.option(ChannelOption.SO_BACKLOG, spec.getBacklog());
    newServer.option(ChannelOption.TCP_NODELAY, true);

    return newServer;
}

From source file:me.jtalk.socketconnector.io.TCPManager.java

License:Open Source License

private Bootstrap instantiateClient() {
    Bootstrap newClient = new Bootstrap();
    newClient.group(this.workers);
    newClient.channel(NioSocketChannel.class);
    newClient.handler(new ChannelInitializer<SocketChannel>() {

        @Override// ww  w. j a va2s. c o m
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new Receiver(TCPManager.this, TCPManager.this.ids.incrementAndGet()))
                    .addLast(new Sender());
        }
    });
    newClient.option(ChannelOption.SO_KEEPALIVE, true);

    return newClient;
}

From source file:net.epsilony.utils.codec.modbus.ModbusClientMaster.java

License:Open Source License

protected ChannelFuture genConnectFuture() {

    initializer = new SimpModbusMasterChannelInitializer();
    initializer.setRequestLifeTime(requestLifeTime);
    bootstrap = new Bootstrap();
    bootstrap.group(group).channelFactory(channelFactory).handler(initializer)
            .option(ChannelOption.TCP_NODELAY, tcpNoDelay).option(ChannelOption.SO_KEEPALIVE, keepAlive)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout)
            .option(ChannelOption.SO_TIMEOUT, socketTimeout);
    return bootstrap.connect(innetAddress, inetPort);
}