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:org.it4y.integration.IT_TProxyListenerTest.java

License:Apache License

@Test
public void testPerformanceMultibleClients() throws Exception {
    final Counter msgcnt = new Counter();
    final Counter errcnt = new Counter();

    LinkManager linkManager = null;//from   w w  w  . ja  v a 2  s.  c  o  m
    TProxyListener proxy = null;

    try {
        linkManager = startLinkManager();
        //get interface with default gateway. this will be our source IP
        final NetworkInterface defaultGW = linkManager.getDefaultGateway();
        log.info("Default GW: {}", defaultGW);

        //Run a proxy to intercept port 80 . this requires setup-test.sh to setup iptables and routing
        proxy = startTProxyListener(new TProxyListener(InetAddress.getByName(bind), port, backlog) {
            public void newClient(TProxyInterceptedSocket client) throws IOException {
                //log.info("intercept client connection: {}", client);
                //check client connection parameters
                Assert.assertNotNull(client);
                //we should check local and remote address are unchanged (thats transparent proxy)
                Assert.assertEquals(0x08080404, client.getRemoteAddress());
                Assert.assertEquals(80, client.getRemotePort());
                Assert.assertTrue(client.getSocket().toString()
                        .contains(defaultGW.getIpv4AddressAsInetAddress().toString()));
                msgcnt.inc();
            }

            public void onIOError(IOException io) {
                errcnt.inc();
                log.info("oeps some error: {}", io.getMessage(), io);
            }
        });
        log.info("TProxy running...");

        //we use NETTY to generated massive tcp connections
        EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 40);
        Bootstrap b = new Bootstrap(); // (1)
        b.group(workerGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)
        b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
        Bootstrap handler = b.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
            }
        });

        // Start the client.
        int nrOfConnections = 1000; //going to high here will cause TO MANY FILES open, you should see man page ulimit ;-)
        log.info("Starting {} connections ....", nrOfConnections);
        long start = System.currentTimeMillis();
        int retry = 0;
        for (int i = 0; i < nrOfConnections; i++) {
            final ChannelFuture f = b.connect("8.8.4.4", 80);
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    //close when connected
                    if (future.isSuccess()) {
                        future.channel().disconnect();
                    } else {
                        log.error("ooeps:", future.cause());
                    }
                }
            });
            Thread.sleep(0, 2000); //sleep a small bit else we see issues in VM's
        }

        //log.info("Started: {} msec", System.currentTimeMillis() - start);
        //wait until all are closed
        while (msgcnt.getCount() < nrOfConnections & retry < nrOfConnections) {
            Thread.sleep(100); //on vm's this can be slow
            retry++;
        }

        long end = System.currentTimeMillis();
        log.info("Done: {} msec", end - start);
        Assert.assertEquals(nrOfConnections, msgcnt.getCount());
        Assert.assertEquals(0, errcnt.getCount());
    } finally {
        if (linkManager != null)
            stopLinkManager(linkManager);
        if (proxy != null)
            stopTProxyListener(proxy);
    }
}

From source file:org.jboss.aerogear.webpush.WebPushClient.java

License:Apache License

public void connect() throws Exception {
    workerGroup = new NioEventLoopGroup();
    try {/*from  ww  w  .jav a 2 s  . c  o  m*/
        final Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(host, port);
        b.handler(new WebPushClientInitializer(configureSsl(), host, port, handler));
        channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + host + ':' + port + "][channelId=" + channel.id() + ']');
    } catch (final Exception e) {
        e.printStackTrace();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.jboss.arquillian.daemon.server.NettyServer.java

License:Apache License

/**
 * {@inheritDoc}//from   w w  w .j av  a  2  s .  c o  m
 *
 * @see org.jboss.arquillian.daemon.server.ServerBase#startInternal()
 */
@Override
protected void startInternal() throws ServerLifecycleException, IllegalStateException {

    // Set up Netty Boostrap
    final ServerBootstrap bootstrap = new ServerBootstrap()
            .group(new NioEventLoopGroup(), new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
            .localAddress(this.getBindAddress()).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(final SocketChannel channel) throws Exception {
                    final ChannelPipeline pipeline = channel.pipeline();
                    NettyServer.this.resetPipeline(pipeline);
                }
            }).childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
    this.bootstrap = bootstrap;

    // Start 'er up
    final ChannelFuture openChannel;
    try {
        openChannel = bootstrap.bind().sync();
    } catch (final InterruptedException ie) {
        Thread.interrupted();
        throw new ServerLifecycleException("Interrupted while awaiting server start", ie);
    } catch (final RuntimeException re) {
        // Exception xlate
        throw new ServerLifecycleException("Encountered error in binding; could not start server.", re);
    }
    // Set bound address
    final InetSocketAddress boundAddress = ((InetSocketAddress) openChannel.channel().localAddress());
    this.setBoundAddress(boundAddress);
}

From source file:org.jdiameter.client.impl.transport.tcp.netty.TCPTransportClient.java

License:Open Source License

public void start() throws InterruptedException {
    logger.debug("Starting TCP Transport on [{}]", socketDescription);
    if (isConnected()) {
        logger.debug("TCP Transport already started, [{}]", socketDescription);
        return;/*from w w  w.j  av a  2 s  . c  o m*/
    }

    this.workerGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("decoder", new DiameterMessageDecoder(parentConnection, parser));
                    pipeline.addLast("encoder", new DiameterMessageEncoder(parser));
                    pipeline.addLast(eventExecutorGroup, "msgHandler",
                            new DiameterMessageHandler(parentConnection));
                }
            });

    this.channel = bootstrap.remoteAddress(destAddress).connect().sync().channel();
    logger.debug("TCP Transport connected successfully, [{}]", socketDescription);

    parentConnection.onConnected();
}

From source file:org.jdiameter.server.impl.io.tcp.netty.NetworkGuard.java

License:Open Source License

private void bind(InetSocketAddress localAddress) {
    logger.debug("Binding to socket [{}]", localAddress);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override// w  w w . ja  v a  2s.  c  o m
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ClientHandler());
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    try {
        channels.add(bootstrap.bind(localAddress).sync().channel());
        logger.debug("Bound to socket [{}]", localAddress);
    } catch (InterruptedException e) {
        logger.error("Failed to bind to socket " + localAddress, e);
    }

    /*
     * bootstrap.bind(port).addListener(new ChannelFutureListener() {
     *
     * @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) {
     * channels.add(channelFuture.channel()); } } });
     */
}

From source file:org.jdiameter.server.impl.io.tls.netty.NetworkGuard.java

License:Open Source License

private void bind(InetSocketAddress localAddress) {
    logger.debug("Binding to socket [{}]", localAddress);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from w  w  w .  ja v a  2s . c  o m
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ClientHandler());
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    try {
        channels.add(bootstrap.bind(localAddress).sync().channel());
        logger.debug("Bound to socket [{}]", localAddress);
    } catch (InterruptedException e) {
        logger.error("Failed to bind to socket " + localAddress, e);
    }
}

From source file:org.jfxvnc.net.SampleVncClient.java

License:Apache License

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

    ProtocolConfiguration config = new DefaultProtocolConfiguration();

    if (args != null && args.length >= 3) {
        config.securityProperty().set(SecurityType.VNC_Auth);
        config.hostProperty().set(args[0]);
        config.portProperty().set(Integer.parseInt(args[1]));
        config.passwordProperty().set(args[2]);
        config.sharedProperty().set(Boolean.TRUE);
    } else {//w w w .ja va 2 s.  c  o m
        System.err.println("arguments missing (host port password)");
        config.securityProperty().set(SecurityType.VNC_Auth);
        config.hostProperty().set("127.0.0.1");
        config.portProperty().set(5902);
        config.passwordProperty().set("vnc");
        config.sharedProperty().set(Boolean.TRUE);
    }

    String host = config.hostProperty().get();
    int port = config.portProperty().get();

    // final SslContext sslContext =
    // SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);

    EventLoopGroup workerGroup = new NioEventLoopGroup(1);
    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.TCP_NODELAY, true);

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

                // use ssl
                // ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
                ch.pipeline().addLast(new ProtocolHandler(new RenderProtocol() {

                    @Override
                    public void render(ImageRect rect, RenderCallback callback) {
                        System.out.println(rect);
                        callback.renderComplete();
                    }

                    @Override
                    public void exceptionCaught(Throwable t) {
                        t.printStackTrace();
                    }

                    @Override
                    public void stateChanged(ProtocolState state) {
                        System.out.println(state);
                    }

                    @Override
                    public void registerInputEventListener(InputEventListener listener) {
                    }

                    @Override
                    public void eventReceived(ServerDecoderEvent evnt) {
                        System.out.println(evnt);
                    }

                }, config));
            }
        });

        ChannelFuture f = b.connect(host, port).sync();

        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:org.jfxvnc.ui.service.VncRenderService.java

License:Apache License

private boolean connect() throws Exception {
    connectProperty.set(true);/*from  w w  w .  j  a  v a2  s  . c om*/
    shutdown();
    workerGroup = new NioEventLoopGroup();

    String host = config.hostProperty().get();
    int port = config.portProperty().get() > 0 ? config.portProperty().get() : CONNECT_PORT;

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);

    b.handler(new ProtocolInitializer(VncRenderService.this, config));

    logger.info("try to connect to {}:{}", host, port);
    ChannelFuture f = b.connect(host, port);
    f.await(5000);

    connectProperty.set(f.isSuccess());
    logger.info("connection {}", connectProperty.get() ? "established" : "failed");
    if (f.isCancelled()) {
        logger.warn("connection aborted");
    } else if (!f.isSuccess()) {
        logger.error("connection failed", f.cause());
        exceptionCaughtProperty.set(f.cause() != null ? f.cause()
                : new Exception("connection failed to host: " + host + ":" + port));
    }
    return connectProperty.get();
}

From source file:org.jmqtt.broker.acceptor.NettyAcceptor.java

License:Open Source License

private void initFactory(String host, int port, final PipelineInitializer pipeliner) {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from   ww  w .  j  a  v  a  2  s  .  c o  m
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    try {
                        pipeliner.init(pipeline);
                    } catch (Throwable th) {
                        LOG.error("Severe error during pipeline creation", th);
                        throw th;
                    }
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(host, port);
        LOG.info("Server binded host: {}, port: {}", host, port);
        f.sync();
    } catch (InterruptedException ex) {
        LOG.error(null, ex);
    }
}

From source file:org.jpos.qrest.RestServer.java

License:Open Source License

@Override
protected void initService() throws GeneralSecurityException, IOException {
    sp = SpaceFactory.getSpace();/*from w w w.  ja v a2s  .  com*/
    final SSLContext sslContext = enableTLS ? getSSLContext() : null;
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    int timeout = cfg.getInt("timeout", 300);
                    ch.pipeline().addLast(new IdleStateHandler(timeout, timeout, timeout));
                    if (enableTLS) {
                        ch.pipeline().addLast(new SslHandler(getSSLEngine(sslContext), true));
                    }
                    ch.pipeline().addLast(new HttpServerCodec());
                    ch.pipeline().addLast(new HttpObjectAggregator(512 * 1024));
                    ch.pipeline().addLast(new RestSession(RestServer.this));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    if (enableTLS) {
        logSSLEngineInfo(getSSLEngine(sslContext));
    }
}