Example usage for io.netty.handler.timeout WriteTimeoutHandler WriteTimeoutHandler

List of usage examples for io.netty.handler.timeout WriteTimeoutHandler WriteTimeoutHandler

Introduction

In this page you can find the example usage for io.netty.handler.timeout WriteTimeoutHandler WriteTimeoutHandler.

Prototype

public WriteTimeoutHandler(int timeoutSeconds) 

Source Link

Document

Creates a new instance.

Usage

From source file:de.jackwhite20.apex.tcp.pipeline.initialize.ApexSocketChannelInitializer.java

License:Open Source License

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

    BackendInfo backendInfo = Apex.getBalancingStrategy().selectBackend(channel.remoteAddress().getHostName(),
            channel.remoteAddress().getPort());

    if (backendInfo == null) {
        // Gracefully close the channel
        channel.close();/*from ww w.j  a  va 2s.co m*/

        logger.error("Unable to select a backend server. All down?");
        return;
    }

    channel.pipeline().addLast(new ReadTimeoutHandler(readTimeout))
            .addLast(new WriteTimeoutHandler(writeTimeout));

    GlobalTrafficShapingHandler trafficShapingHandler = Apex.getInstance().getTrafficShapingHandler();
    if (trafficShapingHandler != null) {
        channel.pipeline().addLast(trafficShapingHandler);
    }

    channel.pipeline().addLast(new SocketUpstreamHandler(backendInfo));

    // Keep track of connections per second
    if (connectionsPerSecondTask != null) {
        connectionsPerSecondTask.inc();
    }

    logger.debug("Connected [{}] <-> [{}:{} ({})]", channel.remoteAddress(), backendInfo.getHost(),
            backendInfo.getPort(), backendInfo.getName());
}

From source file:divconq.bus.Bus.java

License:Open Source License

public void connect() {
    // never try to connect until init has run
    if (Hub.instance.isStopping())
        return;/*from   w w w . ja  v  a2s. c o  m*/

    // if connect method is already running then skip - it will try again later 
    if (!this.connectLock.tryLock())
        return;

    try {
        // ==========================================================================
        //   Add client connections when not enough
        // ==========================================================================

        for (final SocketInfo info : this.connectors.values()) {
            HubRouter router = this.allocateOrGetHub(info.getHubId(), info.isGateway());

            if (router.isLocal())
                continue;

            // -------------------------------------------------
            // message port
            // -------------------------------------------------
            int conncount = router.getCountSessions(info);

            // add a coonection only once per call to connect (should be between 2 - 15 seconds between calls)
            if (conncount < info.getCount()) {
                Bootstrap b = new Bootstrap();

                b.group(this.getEventLoopGroup()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 250)
                        .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();

                                if (info.isUseSsl())
                                    pipeline.addLast("ssl",
                                            new SslHandler(SslContextFactory.getClientEngine()));

                                pipeline.addLast("http-codec", new HttpClientCodec());
                                pipeline.addLast("aggregator", new HttpObjectAggregator(8192)); // TODO is this too small?

                                pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                                pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                                pipeline.addLast("ws-handler", new ClientHandler(info));
                            }
                        });

                Logger.debug("dcBus Client connecting");

                try {
                    // must wait here to make sure we don't release connectLock too soon
                    // we want channel init (above) to complete before we try connect again
                    b.connect(info.getAddress()).sync();
                } catch (InterruptedException x) {
                    Logger.warn("dcBus Client interrupted while connecting: " + x);
                } catch (Exception x) {
                    Logger.debug("dcBus Client unable to connect: " + x);
                }
            }

            // -------------------------------------------------
            // stream port
            // -------------------------------------------------
            conncount = router.getCountStreamSessions(info);

            // add a coonection only once per call to connect (should be between 2 - 15 seconds between calls)
            if (conncount < info.getStreamCount()) {
                Bootstrap b = new Bootstrap();

                b.group(this.getEventLoopGroup()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 250)
                        .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();

                                if (info.isUseSsl())
                                    pipeline.addLast("ssl",
                                            new SslHandler(SslContextFactory.getClientEngine()));

                                // TODO consider compression

                                pipeline.addLast("decoder", new StreamDecoder());
                                pipeline.addLast("encoder", new StreamEncoder());

                                pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                                pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                                pipeline.addLast("handler", new StreamHandler(info, false));
                            }
                        });

                Logger.debug("dcBus Client stream connecting");

                try {
                    // must wait here to make sure we don't release connectLock too soon
                    // we want chanel init (above) to complete before we try connect again
                    b.connect(info.getStreamAddress()).addListener(new GenericFutureListener<ChannelFuture>() {
                        @Override
                        public void operationComplete(ChannelFuture cf) throws Exception {
                            if (!cf.isSuccess()) {
                                Logger.debug("dcBus Stream unable to connect: " + cf.cause());
                                return;
                            }

                            // client starts the HELLO thing once connected!
                            StreamMessage icmd = Hub.instance.getBus().getLocalHub()
                                    .buildStreamHello(info.getHubId());
                            cf.channel().writeAndFlush(icmd);
                        }
                    }).sync();
                } catch (InterruptedException x) {
                    Logger.warn("dcBus Client stream interrupted while connecting: " + x);
                } catch (Exception x) {
                    Logger.debug("dcBus Client stream unable to connect: " + x);
                }
            }
        }

        // ==========================================================================
        //   Add server binding when missing
        // ==========================================================================

        for (final SocketInfo info : this.listeners) {
            // only if not currently bound
            if (this.activelisteners.containsKey(info))
                continue;

            // -------------------------------------------------
            // message port
            // -------------------------------------------------
            ServerBootstrap b = new ServerBootstrap();

            b.group(this.getEventLoopGroup()).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (info.isUseSsl())
                                pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine()));

                            pipeline.addLast("codec-http", new HttpServerCodec());
                            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));

                            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                            pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                            pipeline.addLast("handler", new ServerHandler(info));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // but also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(info.getAddress()).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("dcBus Message Server listening - now listening for dcMessages on TCP port "
                            + info.getPort());
                    this.activelisteners.put(info, bfuture.channel());
                } else
                    Logger.error("dcBus Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.warn("dcBus Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("dcBus Server unable to bind: " + x);
            }

            // -------------------------------------------------
            // stream port
            // -------------------------------------------------
            b = new ServerBootstrap();

            b.group(this.getEventLoopGroup()).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (info.isUseSsl())
                                pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine()));

                            // TODO consider compression

                            pipeline.addLast("decoder", new StreamDecoder());
                            pipeline.addLast("encoder", new StreamEncoder());

                            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                            pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                            pipeline.addLast("handler", new StreamHandler(info, true));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // but also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(info.getStreamAddress()).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("dcBus Stream Server listening - now listening for dcStreams on TCP port "
                            + info.getPort());
                    this.activestreamlisteners.put(info, bfuture.channel());
                } else
                    Logger.error("dcBus Stream Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.warn("dcBus Stream Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("dcBus Stream Server unable to bind: " + x);
            }
        }

        // ==========================================================================
        //   Remove server binding as needed
        // ==========================================================================

        for (final SocketInfo info : this.activelisteners.keySet()) {
            // all is well if in the listeners list
            if (this.listeners.contains(info))
                continue;

            // otherwise we don't want to bind anymore
            this.stopSocketListener(info);
        }
    } finally {
        this.connectLock.unlock();
    }
}

From source file:divconq.ctp.net.CtpServices.java

License:Open Source License

public void connect() {
    // never try to connect until init has run
    if (Hub.instance.isStopping())
        return;/*from  w w w  . j  av a 2s .  c  o  m*/

    // if connect method is already running then skip - it will try again later 
    if (!this.connectLock.tryLock())
        return;

    try {
        // ==========================================================================
        //   Add server binding when missing
        // ==========================================================================

        for (SocketInfo info : this.listeners) {
            // only if not currently bound
            if (this.activelisteners.containsKey(info))
                continue;

            // -------------------------------------------------
            // stream port
            // -------------------------------------------------
            ServerBootstrap b = new ServerBootstrap().group(Hub.instance.getEventLoopGroup())
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (info.isUseSsl())
                                pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine())); // TODO this should be the external SSL not the BUS one 

                            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                            pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(45)); // TODO config

                            //pipeline.addLast("logger", new LoggingHandler(LogLevel.INFO));

                            // start as guest until authenticated
                            CtpAdapter adapter = new CtpAdapter(OperationContext.allocateGuest());
                            adapter.setHandler(new CtpsHandler());

                            pipeline.addLast("ctp", new CtpHandler(adapter, true));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // and also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(info.getAddress()).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("dcCtp Server listening");
                    this.activelisteners.put(info, bfuture.channel());
                } else
                    Logger.error("dcCtp Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.warn("dcCtp Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("dcCtp Server unable to bind: " + x);
            }
        }

        // ==========================================================================
        //   Remove server binding as needed
        // ==========================================================================

        for (final SocketInfo info : this.activelisteners.keySet()) {
            // all is well if in the listeners list
            if (this.listeners.contains(info))
                continue;

            // otherwise we don't want to bind anymore
            this.stopSocketListener(info);
        }
    } finally {
        this.connectLock.unlock();
    }
}

From source file:ru.releng.shameonyou.core.graphite.GraphiteClient.java

License:Apache License

private Bootstrap configureBootstrap(Bootstrap bootstrap, EventLoopGroup eventLoopGroup) {
    return bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
            .remoteAddress(graphiteHost, graphitePort).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024)
            .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 128 * 1024)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*ww w . j a va  2  s.  c o m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("decoder", decoder);
                    ch.pipeline().addLast("encoder", encoder);
                    ch.pipeline().addLast("writeTimeoutHandler", new WriteTimeoutHandler(1));
                    ch.pipeline().addLast("handler", handler);
                }
            });
}