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:com.flysoloing.learning.network.netty.spdy.client.SpdyClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.NPN,
                    // 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.SPDY_3_1,
                    ApplicationProtocolNames.HTTP_1_1))
            .build();/* w  ww .j  a  v  a 2s  . c  o m*/

    HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler));

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to " + HOST + ':' + PORT);

        // Create a GET request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
        request.headers().set(HttpHeaderNames.HOST, HOST);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Send the GET request.
        channel.writeAndFlush(request).sync();

        // Waits for the complete HTTP response
        httpResponseHandler.queue().take().sync();
        System.out.println("Finished SPDY HTTP GET");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.foilen.smalltools.net.netty.NettyClient.java

License:Open Source License

public void connect(String hostname, int port, final RSATrustedCertificates trustedCertificates,
        final RSACertificate certificate, final List<ChannelHandlerContainer> channelHandlerContainers) {

    AssertTools.assertNull(channel, "Client is already connected");

    try {/*  w w  w.  j  a  va 2 s.  com*/
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(NettyCommon.EVENT_LOOP_GROUP);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel socketChannel) throws Exception {

                // Add sslCtx if needed
                if (trustedCertificates != null || certificate != null) {
                    TrustManagerFactory trustManagerFactory = trustedCertificates == null ? null
                            : RSATools.createTrustManagerFactory(trustedCertificates);
                    KeyManagerFactory keyManagerFactory = certificate == null ? null
                            : RSATools.createKeyManagerFactory(certificate);

                    CipherSuiteFilter cipherFilter = IdentityCipherSuiteFilter.INSTANCE;
                    SslContext sslCtx = SslContext.newClientContext(SslProvider.JDK, null, trustManagerFactory,
                            null, null, null, keyManagerFactory, null, cipherFilter, null, 0, 0);
                    socketChannel.pipeline().addLast(sslCtx.newHandler(socketChannel.alloc()));
                }

                // Add the channel handlers
                for (ChannelHandlerContainer channelHandlerContainer : channelHandlerContainers) {
                    socketChannel.pipeline()
                            .addLast(ReflectionTools.instantiate(
                                    channelHandlerContainer.getChannelHandlerClass(),
                                    channelHandlerContainer.getConstructorParams()));
                }

            }
        });

        logger.info("Connecting to {}:{}", hostname, port);
        channel = bootstrap.connect(hostname, port).sync().channel();
    } catch (InterruptedException e) {
        logger.info("Connection to {}:{} was interrupted while being created", hostname, port);
        throw new SmallToolsException("Connection was interrupted");
    }

}

From source file:com.foilen.smalltools.net.netty.NettyServer.java

License:Open Source License

/**
 * Start the server./*w  ww. j av a  2s .com*/
 *
 * @param port
 *            the port to listen on (0 for a random port ; get it with {@link #getPort()})
 * @param trustedCertificates
 *            (optional) the certificate to trust connections from
 * @param certificate
 *            (optional) the server's certificate
 * @param channelHandlerContainers
 *            the channel handlers for the incoming connections
 */
public void start(final int port, final RSATrustedCertificates trustedCertificates,
        final RSACertificate certificate, final List<ChannelHandlerContainer> channelHandlerContainers) {

    AssertTools.assertNull(thread, "Server is already started");

    final CountDownLatch countDownLatch = new CountDownLatch(1);
    thread = new Thread(() -> {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(NettyCommon.EVENT_LOOP_GROUP, NettyCommon.EVENT_LOOP_GROUP);
            serverBootstrap.channel(NioServerSocketChannel.class);

            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    InetSocketAddress remoteAddress = socketChannel.remoteAddress();
                    logger.info("Got a connection from {}:{}", remoteAddress.getHostName(),
                            remoteAddress.getPort());

                    // Add sslCtx if needed
                    if (trustedCertificates != null || certificate != null) {
                        TrustManagerFactory trustManagerFactory = trustedCertificates == null ? null
                                : RSATools.createTrustManagerFactory(trustedCertificates);
                        KeyManagerFactory keyManagerFactory = certificate == null ? null
                                : RSATools.createKeyManagerFactory(certificate);

                        CipherSuiteFilter cipherFilter = IdentityCipherSuiteFilter.INSTANCE;
                        SslContext sslCtx = SslContext.newServerContext(SslProvider.JDK, null,
                                trustManagerFactory, null, null, null, keyManagerFactory, null, cipherFilter,
                                null, 0, 0);
                        SslHandler sslHandler = sslCtx.newHandler(socketChannel.alloc());

                        if (trustManagerFactory == null) {
                            logger.debug("Will not verify client's identity");
                        } else {
                            logger.debug("Will verify client's identity");
                            SSLEngine sslEngine = sslHandler.engine();
                            sslEngine.setNeedClientAuth(true);
                        }

                        socketChannel.pipeline().addLast(sslHandler);
                    }

                    // Add the channel handlers
                    for (ChannelHandlerContainer channelHandlerContainer : channelHandlerContainers) {
                        socketChannel.pipeline()
                                .addLast(ReflectionTools.instantiate(
                                        channelHandlerContainer.getChannelHandlerClass(),
                                        channelHandlerContainer.getConstructorParams()));
                    }
                }
            }) //
                    .option(ChannelOption.SO_BACKLOG, 128) //
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            bindedPort = port;
            logger.info("Server on port {} is starting...", port);
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            SocketAddress socketAddress = channelFuture.channel().localAddress();
            if (socketAddress instanceof InetSocketAddress) {
                InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
                bindedPort = inetSocketAddress.getPort();
            }
            logger.info("Server on port {} is started", bindedPort);
            countDownLatch.countDown();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.info("Server on port {} is interrupted", bindedPort);
        } finally {
            countDownLatch.countDown();
        }
        logger.info("Server on port {} is stopped", bindedPort);
    });
    thread.setName("Netty Server-" + bindedPort);
    thread.start();

    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        logger.error("Interrupted while waiting for the server to start");
    }
}

From source file:com.fsocks.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }/*from   w  w  w . j av  a2  s .  c o  m*/
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    //??successclient
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS,
                                    request.dstAddrType(), request.dstAddr(), request.dstPort()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        public void operationComplete(ChannelFuture channelFuture) {
                            //clientremote???????local proxy
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
        //?
        logger.info("? addressType : " + request.dstAddrType() + ", cmdType:" + request.type()
                + ", host:" + request.dstAddr() + ", port:" + request.dstPort());
        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                    logger.info("?? addressType : " + request.dstAddrType()
                            + ", cmdType:" + request.type() + ", host:" + request.dstAddr() + ", port:"
                            + request.dstPort());
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.gemstone.gemfire.redis.GemFireRedisServer.java

License:Apache License

/**
 * Helper method to start the server listening for connections. The
 * server is bound to the port specified by {@link GemFireRedisServer#serverPort}
 * /*w ww  .j ava 2  s .c o  m*/
 * @throws IOException
 * @throws InterruptedException
 */
private void startRedisServer() throws IOException, InterruptedException {
    ThreadFactory selectorThreadFactory = new ThreadFactory() {
        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GemFireRedisServer-SelectorThread-" + counter.incrementAndGet());
            t.setDaemon(true);
            return t;
        }

    };

    ThreadFactory workerThreadFactory = new ThreadFactory() {
        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GemFireRedisServer-WorkerThread-" + counter.incrementAndGet());
            return t;
        }

    };

    bossGroup = null;
    workerGroup = null;
    Class<? extends ServerChannel> socketClass = null;
    if (singleThreadPerConnection) {
        bossGroup = new OioEventLoopGroup(Integer.MAX_VALUE, selectorThreadFactory);
        workerGroup = new OioEventLoopGroup(Integer.MAX_VALUE, workerThreadFactory);
        socketClass = OioServerSocketChannel.class;
    } else {
        bossGroup = new NioEventLoopGroup(this.numSelectorThreads, selectorThreadFactory);
        workerGroup = new NioEventLoopGroup(this.numWorkerThreads, workerThreadFactory);
        socketClass = NioServerSocketChannel.class;
    }
    InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem();
    String pwd = system.getConfig().getRedisPassword();
    final byte[] pwdB = Coder.stringToBytes(pwd);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(socketClass).childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (logger.fineEnabled())
                logger.fine("GemFireRedisServer-Connection established with " + ch.remoteAddress());
            ChannelPipeline p = ch.pipeline();
            p.addLast(ByteToCommandDecoder.class.getSimpleName(), new ByteToCommandDecoder());
            p.addLast(ExecutionHandlerContext.class.getSimpleName(),
                    new ExecutionHandlerContext(ch, cache, regionCache, GemFireRedisServer.this, pwdB));
        }
    }).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, getBufferSize())
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, GemFireRedisServer.connectTimeoutMillis)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // Bind and start to accept incoming connections.
    ChannelFuture f = b.bind(new InetSocketAddress(getBindAddress(), serverPort)).sync();
    if (this.logger.infoEnabled()) {
        String logMessage = "GemFireRedisServer started {" + getBindAddress() + ":" + serverPort
                + "}, Selector threads: " + this.numSelectorThreads;
        if (this.singleThreadPerConnection)
            logMessage += ", One worker thread per connection";
        else
            logMessage += ", Worker threads: " + this.numWorkerThreads;
        this.logger.info(logMessage);
    }
    this.serverChannel = f.channel();
}

From source file:com.ghrum.common.protocol.CommonConnectionManager.java

License:Apache License

/**
 * Initialise the server connection//www  . ja  v  a2 s . c o m
 *
 * @param configuration the configuration of the connection
 */
public void initialise(Protocol configuration) {
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ProtocolChannelInitializer(protocol.getMessageService(), null)) // null -> handler
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
}

From source file:com.github.jrialland.ajpclient.pool.Channels.java

License:Apache License

public static Bootstrap newBootStrap(final String host, final int port, final EventLoopGroup eventLoopGroup) {
    return new Bootstrap().group(getEventLoopGroup()).remoteAddress(host, port).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.AUTO_READ, true);
}

From source file:com.github.lburgazzoli.quickfixj.transport.netty.NettySocketInitiator.java

License:Apache License

/**
 *
 */// w ww. jav a 2s  .com
@Override
public void connect() {
    try {
        m_boot = new Bootstrap();
        m_boot.group(new NioEventLoopGroup());
        m_boot.channel(NioSocketChannel.class);
        m_boot.option(ChannelOption.SO_KEEPALIVE, true);
        m_boot.option(ChannelOption.TCP_NODELAY, true);
        m_boot.option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        m_boot.handler(new NettyChannelInitializer(this, getHelper(), FIXSessionType.INITIATOR));

        getHelper().getSession().getSessionID();
        String host = getHelper().getSettings().getString("SocketConnectHost");
        int port = getHelper().getSettings().getInt("SocketConnectPort");

        m_boot.remoteAddress(new InetSocketAddress(host, port));

        if (!isRunning()) {
            setRunning(true);
            doConnect();
        }
    } catch (Exception e) {
        LOGGER.warn("Exception", e);
        setRunning(false);
    }
}

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 {/*  w  ww .ja v a2  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 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 {/*from   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();
    }
}