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:org.Client.NettyClient.java

License:Apache License

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

    // ?NIO//from   w ww .j  av a  2 s . co  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(new Runnable() {
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    try {
                        connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ???
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

From source file:org.diorite.impl.client.connection.ClientConnectionChannel.java

License:Open Source License

@Override
protected void initChannel(final Channel channel) throws Exception {
    try {// www  .j a  v a2  s .c om
        channel.config().setOption(ChannelOption.IP_TOS, IP_TOS);
    } catch (final ChannelException ignored) {
    }
    try {
        channel.config().setOption(ChannelOption.TCP_NODELAY, false);
    } catch (final ChannelException ignored) {
    }
    channel.pipeline().addLast("timeout", new ReadTimeoutHandler(TIMEOUT_SECONDS))
            .addLast("sizer", new PacketSizer()).addLast("codec", new PacketCodec(this.clientConnection));
    final NetworkManager networkmanager = new NetworkManager(this.clientConnection.getCore());
    this.clientConnection.setConnection(networkmanager);

    channel.pipeline().addLast("packet_handler", networkmanager);
    networkmanager.setPacketListener(new HandshakeListener(this.clientConnection.getCore(), networkmanager));
}

From source file:org.diorite.impl.server.connection.ServerConnectionChannel.java

License:Open Source License

@Override
protected void initChannel(final Channel channel) throws Exception {
    try {/*from w  ww .java2 s  .  co m*/
        channel.config().setOption(ChannelOption.IP_TOS, IP_TOS);
    } catch (final ChannelException ignored) {
    }
    try {
        channel.config().setOption(ChannelOption.TCP_NODELAY, false);
    } catch (final ChannelException ignored) {
    }
    channel.pipeline().addLast("timeout", new ReadTimeoutHandler(TIMEOUT_SECONDS))
            .addLast("sizer", new PacketSizer()).addLast("codec", new PacketCodec(this.serverConnection)); //.addLast("legacy_query", new LegacyPingHandler(this.connectionHandler)).addLast("splitter", new PacketSplitter()).addLast("decoder", new PacketDecoder(EnumProtocolDirection.SERVERBOUND)).addLast("prepender", new PacketPrepender()).addLast("encoder", new PacketEncoder(EnumProtocolDirection.CLIENTBOUND));
    final NetworkManager networkmanager = new NetworkManager(this.serverConnection.getCore());

    this.serverConnection.getConnections().add(networkmanager);
    channel.pipeline().addLast("packet_handler", networkmanager);
    networkmanager.setPacketListener(new HandshakeListener(this.serverConnection.getCore(), networkmanager));
}

From source file:org.lanternpowered.pingy.Pingy.java

License:MIT License

/**
 * Starts the pingy server.//from  w w w  .j a  v  a 2  s  .c  o m
 *
 * @throws IOException
 */
public void start() throws IOException {
    boolean epoll = false;

    if (this.properties.isUseEpollWhenAvailable()) {
        if (Epoll.isAvailable()) {
            debugInfo("Epoll is available");
            epoll = true;
        } else {
            debugWarn(
                    "Epoll is unavailable (The following exception is only used to print the cause why it's unavailable, "
                            + "it won't affect the functionality.)");
            //noinspection ThrowableResultOfMethodCallIgnored
            debug(() -> Epoll.unavailabilityCause().printStackTrace());
        }
    }

    final ServerBootstrap bootstrap = new ServerBootstrap();
    final EventLoopGroup group = epoll ? new EpollEventLoopGroup() : new NioEventLoopGroup();

    final ChannelFuture future = bootstrap.group(group)
            .channel(epoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ReadTimeoutHandler(20))
                            .addLast(new PingyLegacyHandler(properties)).addLast(new PingyFramingHandler())
                            .addLast(new PingyHandler(properties));
                }
            }).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .bind(getBindAddress(this.properties.getIp(), this.properties.getPort()));
    final Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
        final Throwable cause = future.cause();
        if (cause instanceof BindException) {
            throw (BindException) cause;
        }
        throw new RuntimeException("Failed to bind to address", cause);
    }
    info("Successfully bound to: " + channel.localAddress());
}

From source file:org.lanternpowered.server.network.NetworkManager.java

License:MIT License

@Override
protected ChannelFuture init0(SocketAddress address, boolean epoll) {
    this.bootstrap = new ServerBootstrap();
    // Take advantage of the fast thread local threads,
    // this is also provided by the default thread factory
    final ThreadFactory threadFactory = ThreadHelper
            .newFastThreadLocalThreadFactory(() -> "netty-" + threadCounter.getAndIncrement());
    this.bossGroup = createEventLoopGroup(epoll, threadFactory);
    this.workerGroup = createEventLoopGroup(epoll, threadFactory);
    this.socketAddress = address;
    return this.bootstrap.group(this.bossGroup, this.workerGroup).channel(getServerSocketChannelClass(epoll))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   ww  w  . j  a v  a  2s . c o  m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    final ChannelPipeline pipeline = ch.pipeline();
                    final NetworkSession networkSession = new NetworkSession(ch, server, NetworkManager.this);
                    final CodecContext codecContext = new SimpleCodecContext(
                            new LanternByteBufferAllocator(ch.alloc()), ch, networkSession);
                    pipeline.addLast(new ReadTimeoutHandler(NetworkSession.READ_TIMEOUT_SECONDS))
                            .addLast(NetworkSession.LEGACY_PING, new LegacyProtocolHandler(networkSession))
                            .addLast(NetworkSession.ENCRYPTION, NoopHandler.INSTANCE)
                            .addLast(NetworkSession.FRAMING, new MessageFramingHandler())
                            .addLast(NetworkSession.COMPRESSION, NoopHandler.INSTANCE)
                            .addLast(NetworkSession.CODECS, new MessageCodecHandler(codecContext))
                            .addLast(NetworkSession.PROCESSOR, new MessageProcessorHandler(codecContext))
                            .addLast(NetworkSession.HANDLER, networkSession);
                }
            }).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .bind(address);
}

From source file:org.onosproject.openflow.controller.impl.OFChannelInitializer.java

License:Apache License

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

    OFChannelHandler handler = new OFChannelHandler(controller);

    ChannelPipeline pipeline = ch.pipeline();
    if (sslContext != null) {
        log.info("OpenFlow SSL enabled.");
        SSLEngine sslEngine = sslContext.createSSLEngine();

        sslEngine.setNeedClientAuth(true);
        sslEngine.setUseClientMode(false);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);

        SslHandler sslHandler = new SslHandler(sslEngine);
        pipeline.addLast("ssl", sslHandler);
    } else {/*from   w  w  w  .  j  a  v  a2  s  . com*/
        log.debug("OpenFlow SSL disabled.");
    }
    pipeline.addLast("ofmessageencoder", OFMessageEncoder.getInstance());
    pipeline.addLast("ofmessagedecoder", OFMessageDecoder.getInstance());

    pipeline.addLast("idle", new IdleStateHandler(20, 25, 0));
    pipeline.addLast("timeout", new ReadTimeoutHandler(30));

    // XXX S ONOS: was 15 increased it to fix Issue #296
    pipeline.addLast("handshaketimeout", new HandshakeTimeoutHandler(handler, 60));
    // ExecutionHandler equivalent now part of Netty core
    if (pipelineExecutor != null) {
        pipeline.addLast(pipelineExecutor, "handler", handler);
    } else {
        pipeline.addLast("handler", handler);
    }
}

From source file:org.tiger.netty.rpc.all.client.NettyClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    try {//  w  w  w .  j av a  2 s.  c o  m
        //Netty?
        Bootstrap b = new Bootstrap();
        b.group(group)
                //Channel
                .channel(NioSocketChannel.class)
                //TCP?NIO?BIO?????
                //SO_TIMEOUT:??0??
                //SO_SNDBUF:???
                //SO_RCVBUF:?
                //SO_REUSEADDR:??ServerSocket???ServerSocketServerSocket??
                //SO_REUSEADDR????????????
                //CONNECT_TIMEOUT_MILLIS:NIO????Netty
                //TCP_NODELAY:?TCP_NODELAY?Nagle?Nagle
                .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        //new LengthFieldBasedFrameDecoder(100000000,0,4,0,4)
                        //??
                        //??????030
                        //??44
                        //???
                        //????4????
                        ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));
                        ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder());//Handler
                        ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                        ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler());
                        ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler());
                    }
                });
        //?????NioSocketChannel?
        //?????????????
        ChannelFuture future = b.connect(new InetSocketAddress(host, port),
                new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync();
        future.channel().closeFuture().sync();
    } finally {
        // ????????
        executor.execute(new Runnable() {
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    try {
                        connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ???
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

From source file:org.tiger.netty.rpc.all.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    //??NIO/*from  w  ww  .  jav  a2s.c o m*/
    //????EventLoopGroup
    //NioEventLoopGroupReactor
    //???boss?Reactor?
    //???worker??IOReactor?
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    //Netty??
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
            //Channel????????
            .channel(NioServerSocketChannel.class)
            //TCP?
            //backlog???
            //??TCP??
            //??listen?syn(connect)??
            //????syn???(?synack)
            // ????????
            //accept???????
            //backlog5?Web??lighttpd128*8
            //???syn??
            //Nettybacklog100???
            .option(ChannelOption.SO_BACKLOG, 100)
            //?HandlerHandler???HandlerNioServerSocketChannelChannelPipelineHandler
            //HandlerSocketChannelChannelPipelineHandler
            .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 future = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();
    System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
    future.channel().closeFuture().sync();
}

From source file:org.virtue.network.Network.java

License:Open Source License

/**
 * Binds a pipeline to a port//from w  w w . j av a 2  s  .com
 */
public void bindNetwork() {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("decoder", new HandshakeDecoder());
                    pipeline.addLast("read-timeout", new ReadTimeoutHandler(15));
                    pipeline.addLast("channel-handler", new NetworkHandler());
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    try {
        future = bootstrap.bind(Constants.SERVER_PORT).sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    logger.info("Bound Virtue on: " + future.channel().localAddress().toString());
}

From source file:org.virtue.network.NetworkPipeline.java

License:Open Source License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    pipeline = ch.pipeline();// w  w  w  . j  av  a2 s.  c  o m
    pipeline.addFirst("decoder", new HandshakeDecoder());
    pipeline.addAfter("decoder", "timeout", new ReadTimeoutHandler(15));
    pipeline.addLast("channel-handler", new NetworkHandler());
}