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

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

Introduction

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

Prototype

public ReadTimeoutHandler(int timeoutSeconds) 

Source Link

Document

Creates a new instance.

Usage

From source file:com.nanxiaoqiang.test.netty.protocol.demo1.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO/*from  w  w w .  j  a va 2  s  .c  om*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws IOException {
                    ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));// ?
                    ch.pipeline().addLast(new NettyMessageEncoder());// ?
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));// ??
                    ch.pipeline().addLast(new LoginAuthRespHandler());// 
                    ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());// 
                }
            });

    // ???
    ChannelFuture cf = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT);
    cf.channel().closeFuture().sync();
    System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
}

From source file:com.net.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO//w w w  .  ja va 2s .co  m
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws IOException {
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                    ch.pipeline().addLast(new ServerHandler(redisTemplate));
                }
            });

    // ???
    b.bind(ContantUtil.port).sync();
    System.out.println("Netty server start ok : " + ("127.0.0.1" + " : " + ContantUtil.port));
}

From source file:com.phei.netty.chapter12.netty.client.NettyClient.java

License:Apache License

public void connect(int port, String host) throws Exception {

    // ?NIO/* w  ww  .jav a2 s  .c o  m*/
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));
                        ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder());
                        ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                        ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler());
                        ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler());
                    }
                });
        // ??
        ChannelFuture future = b.connect(new InetSocketAddress(host, port),
                new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync();
        future.channel().closeFuture().sync();
    } finally {
        // ????????
        executor.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                try {
                    connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ???
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}

From source file:com.phei.netty.protocol.netty.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO//w  w w  . j  ava  2 s . c om
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
            //abstractBootstraphandlerNioServerSocketChannel
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws IOException {
                    //?ServerBootstraphandlersocketchannel
                    ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));
                    ch.pipeline().addLast(new NettyMessageEncoder());
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                    ch.pipeline().addLast(new LoginAuthRespHandler());
                    ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());
                }
            });

    // ???
    b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();
    System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
}

From source file:com.relayrides.pushy.apns.FeedbackServiceConnection.java

License:Open Source License

/**
 * <p>Connects to the APNs feedback service and waits for expired tokens to arrive. Be warned that this is a
 * <strong>destructive operation</strong>. According to Apple's documentation:</p>
 *
 * <blockquote>The feedback service's list is cleared after you read it. Each time you connect to the feedback
 * service, the information it returns lists only the failures that have happened since you last
 * connected.</blockquote>// ww w.j ava2 s. c om
 */
public synchronized void connect() {

    if (this.connectFuture != null) {
        throw new IllegalStateException(String.format("%s already started a connection attempt.", this.name));
    }

    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);

    final FeedbackServiceConnection feedbackConnection = this;
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();

            final SSLEngine sslEngine = feedbackConnection.sslContext.createSSLEngine();
            sslEngine.setUseClientMode(true);

            pipeline.addLast("ssl", new SslHandler(sslEngine));
            pipeline.addLast("readTimeoutHandler",
                    new ReadTimeoutHandler(feedbackConnection.configuration.getReadTimeout()));
            pipeline.addLast("decoder", new ExpiredTokenDecoder());
            pipeline.addLast("handler", new FeedbackClientHandler(feedbackConnection));
        }
    });

    this.connectFuture = bootstrap.connect(this.environment.getFeedbackHost(),
            this.environment.getFeedbackPort());
    this.connectFuture.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(final ChannelFuture connectFuture) {

            if (connectFuture.isSuccess()) {
                log.debug("{} connected; waiting for TLS handshake.", feedbackConnection.name);

                final SslHandler sslHandler = connectFuture.channel().pipeline().get(SslHandler.class);

                try {
                    sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {

                        @Override
                        public void operationComplete(final Future<Channel> handshakeFuture) {
                            if (handshakeFuture.isSuccess()) {
                                log.debug("{} successfully completed TLS handshake.", feedbackConnection.name);

                                if (feedbackConnection.listener != null) {
                                    feedbackConnection.listener.handleConnectionSuccess(feedbackConnection);
                                }

                            } else {
                                log.debug("{} failed to complete TLS handshake with APNs feedback service.",
                                        feedbackConnection.name, handshakeFuture.cause());

                                connectFuture.channel().close();

                                if (feedbackConnection.listener != null) {
                                    feedbackConnection.listener.handleConnectionFailure(feedbackConnection,
                                            handshakeFuture.cause());
                                }
                            }
                        }
                    });
                } catch (NullPointerException e) {
                    log.warn("{} failed to get SSL handler and could not wait for a TLS handshake.",
                            feedbackConnection.name);

                    connectFuture.channel().close();

                    if (feedbackConnection.listener != null) {
                        feedbackConnection.listener.handleConnectionFailure(feedbackConnection, e);
                    }
                }
            } else {
                log.debug("{} failed to connect to APNs feedback service.", feedbackConnection.name,
                        connectFuture.cause());

                if (feedbackConnection.listener != null) {
                    feedbackConnection.listener.handleConnectionFailure(feedbackConnection,
                            connectFuture.cause());
                }
            }
        }
    });
}

From source file:com.rs3e.network.ChannelChildHandler.java

License:Open Source License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ch.pipeline().addLast(new ReadTimeoutHandler(5), new HandshakeDecoder(),
            new ServerChannelAdapterHandler(mainContext));
}

From source file:com.streamsets.pipeline.stage.origin.tcp.TCPServerSource.java

License:Apache License

private void createAndStartTCPServer(List<ConfigIssue> issues, String portsField) {
    tcpServer = new TCPConsumingServer(config.enableEpoll, config.numThreads, addresses,
            new ChannelInitializer<SocketChannel>() {
                @Override/*from  ww w.ja  va 2 s.  c  o  m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    if (config.tlsConfigBean.isEnabled()) {
                        // Add TLS handler into pipeline in the first position
                        ch.pipeline().addFirst("TLS", new SslHandler(config.tlsConfigBean.createSslEngine()));
                    }

                    ch.pipeline().addLast(
                            // first, decode the ByteBuf into some POJO type extending MessageToRecord
                            buildByteBufToMessageDecoderChain(issues).toArray(new ChannelHandler[0]));

                    ch.pipeline().addLast(
                            // next, handle MessageToRecord instances to build SDC records and errors
                            new TCPObjectToRecordHandler(getContext(), config.batchSize, config.maxWaitTime,
                                    pipelineIdsToFail::put, getContext().createELEval(RECORD_PROCESSED_EL_NAME),
                                    getContext().createELVars(), config.recordProcessedAckMessage,
                                    getContext().createELEval(BATCH_COMPLETED_EL_NAME),
                                    getContext().createELVars(), config.batchCompletedAckMessage,
                                    config.timeZoneID, Charset.forName(config.ackMessageCharset)));

                    if (config.readTimeout > 0) {
                        ch.pipeline().addLast(new ReadTimeoutHandler(config.readTimeout));
                    }
                }
            });
    if (issues.isEmpty()) {
        try {
            tcpServer.listen();
            tcpServer.start();
        } catch (Exception ex) {
            tcpServer.destroy();
            tcpServer = null;

            if (ex instanceof SocketException && privilegedPortUsage) {
                issues.add(getContext().createConfigIssue(Groups.TCP.name(), portsField, Errors.TCP_04,
                        config.ports, ex));
            } else {
                LOG.debug("Caught exception while starting up TCP server: {}", ex);
                issues.add(getContext().createConfigIssue(null, null, Errors.TCP_00, addresses.toString(),
                        ex.toString(), ex));
            }
        }
    }
}

From source file:com.zz.learning.netty5.chap12.client.NettyClient.java

License:Apache License

public void connect(int port, String host) throws Exception {

    // ?NIO//from  www.  ja  v a 2s .  c  om
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024));
                        // ch.pipeline().addLast(new
                        // NettyMessageDecoder(1024 * 1024, 4, 4));
                        ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder());
                        ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                        ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler());
                        ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler());
                        ch.pipeline().addLast("businessMessageHandler", new BusinessMessageReqHandler());
                    }
                });
        // ??
        ChannelFuture future = b.connect(new InetSocketAddress(host, port),
                new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync();
        channel = future.channel();
        channel.closeFuture().sync();
        // future.channel().closeFuture().sync();
        // return future.channel();
    } finally {
        // ????????

        /*
         * executor.execute(new Runnable() {
         * 
         * @Override public void run() { try { TimeUnit.SECONDS.sleep(1);
         * try { if(channel==null||!channel.isActive())
         * connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ??? }
         * catch (Exception e) { e.printStackTrace(); } } catch
         * (InterruptedException e) { e.printStackTrace(); } } });
         */

    }
}

From source file:com.zz.learning.netty5.chap12.server.NettyServer.java

License:Apache License

private void bind() throws Exception {
    // ??NIO//w ww.  j  av  a2s.c  om
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws IOException {
                    ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024));
                    // ch.pipeline().addLast(new NettyMessageDecoder(1024 *
                    // 1024, 4, 4));
                    ch.pipeline().addLast(new NettyMessageEncoder());
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                    ch.pipeline().addLast(new LoginAuthRespHandler());
                    ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());
                    ch.pipeline().addLast("BusinessMessageRespHandler", new BusinessMessageRespHandler());
                }
            });

    // ???
    ChannelFuture cf = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();
    //  serverChannel = cf.channel();
    System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
}

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 w w w.  jav a  2 s  .c  om

        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());
}