Search in sources :

Example 41 with IdleStateHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project java by wavefrontHQ.

the class HistogramLineIngester method initChannel.

@Override
protected void initChannel(Channel ch) throws Exception {
    // Round robin channel to handler assignment.
    int idx = (int) (Math.abs(connectionId.getAndIncrement()) % handlers.size());
    ChannelHandler handler = handlers.get(idx);
    // Add decoders and timeout, add handler()
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new LineBasedFrameDecoder(MAXIMUM_FRAME_LENGTH, true, false), new StringDecoder(Charsets.UTF_8), new IdleStateHandler(CHANNEL_IDLE_TIMEOUT_IN_SECS_DEFAULT, 0, 0), new ChannelDuplexHandler() {

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
                    logger.warning("terminating connection to histogram client due to inactivity after " + CHANNEL_IDLE_TIMEOUT_IN_SECS_DEFAULT + "s: " + ctx.channel());
                    ctx.close();
                }
            }
        }
    }, handler);
}
Also used : IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) BindException(java.net.BindException)

Example 42 with IdleStateHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project web3sdk by FISCO-BCOS.

the class ChannelConnections method startConnect.

public void startConnect() {
    if (running) {
        logger.debug("服务已启动");
        return;
    }
    logger.debug("初始化connections connect");
    // 初始化netty
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    bootstrap.group(workerGroup);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    final ChannelConnections selfService = this;
    final ThreadPoolTaskExecutor selfThreadPool = threadPool;
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    final Resource keystoreResource = resolver.getResource(getClientKeystorePath());
    final Resource caResource = resolver.getResource(getCaCertPath());
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            KeyStore ks = KeyStore.getInstance("JKS");
            InputStream ksInputStream = keystoreResource.getInputStream();
            ks.load(ksInputStream, getKeystorePassWord().toCharArray());
            /*
				 * 每次连接使用新的handler 连接信息从socketChannel中获取
				 */
            ChannelHandler handler = new ChannelHandler();
            handler.setConnections(selfService);
            handler.setIsServer(false);
            handler.setThreadPool(selfThreadPool);
            SslContext sslCtx = SslContextBuilder.forClient().trustManager(caResource.getFile()).keyManager((PrivateKey) ks.getKey("client", getClientCertPassWord().toCharArray()), (X509Certificate) ks.getCertificate("client")).build();
            ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new LengthFieldBasedFrameDecoder(1024 * 1024 * 4, 0, 4, -4, 0), new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS), handler);
        }
    });
    running = true;
    Thread loop = new Thread() {

        public void run() {
            try {
                while (true) {
                    if (!running) {
                        return;
                    }
                    // 尝试重连
                    reconnect();
                    Thread.sleep(heartBeatDelay);
                }
            } catch (InterruptedException e) {
                logger.error("系统错误", e);
            }
        }
    };
    loop.start();
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) ResourcePatternResolver(org.springframework.core.io.support.ResourcePatternResolver) InputStream(java.io.InputStream) Resource(org.springframework.core.io.Resource) KeyStore(java.security.KeyStore) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 43 with IdleStateHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project web3sdk by FISCO-BCOS.

the class ChannelConnections method startConnect.

public void startConnect() throws Exception {
    if (running) {
        logger.debug("running");
        return;
    }
    logger.debug(" start connect. ");
    // init netty
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    bootstrap.group(workerGroup);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    // set connect timeout
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout);
    final ChannelConnections selfService = this;
    final ThreadPoolTaskExecutor selfThreadPool = threadPool;
    SslContext sslContext = (EncryptType.encryptType == EncryptType.ECDSA_TYPE) ? initSslContext() : initSMSslContext();
    SslContext finalSslContext = sslContext;
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            /*
                         * Each connection is fetched from the socketChannel, using the new
                         * handler connection information
                         */
            ChannelHandler handler = new ChannelHandler();
            handler.setConnections(selfService);
            handler.setThreadPool(selfThreadPool);
            SslHandler sslHandler = finalSslContext.newHandler(ch.alloc());
            /**
             * set ssl handshake timeout
             */
            sslHandler.setHandshakeTimeoutMillis(sslHandShakeTimeout);
            ch.pipeline().addLast(sslHandler, new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, -4, 0), new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS), handler);
        }
    });
    List<Tuple3<String, Integer, ChannelFuture>> tuple3List = new ArrayList<>();
    // try to connect to all nodes
    for (ConnectionInfo connectionInfo : connections) {
        String IP = connectionInfo.getHost();
        Integer port = connectionInfo.getPort();
        ChannelFuture channelFuture = bootstrap.connect(IP, port);
        tuple3List.add(new Tuple3<>(IP, port, channelFuture));
    }
    boolean atLeastOneConnectSuccess = false;
    List<String> errorMessageList = new ArrayList<>();
    // Wait for all connection operations to complete
    for (Tuple3<String, Integer, ChannelFuture> tuple3 : tuple3List) {
        ChannelFuture connectFuture = tuple3.getValue3().awaitUninterruptibly();
        if (!connectFuture.isSuccess()) {
            logger.error(" connect to {}:{}, error: {}", tuple3.getValue1(), tuple3.getValue2(), connectFuture.cause().getMessage());
            String connectFailedMessage = Objects.isNull(connectFuture.cause()) ? "connect to " + tuple3.getValue1() + ":" + tuple3.getValue2() + " failed" : connectFuture.cause().getMessage();
            errorMessageList.add(connectFailedMessage);
        } else {
            // tcp connect success and waiting for SSL handshake
            logger.trace(" connect to {}:{} success", tuple3.getValue1(), tuple3.getValue2());
            SslHandler sslhandler = connectFuture.channel().pipeline().get(SslHandler.class);
            if (Objects.isNull(sslhandler)) {
                String sslHandshakeFailedMessage = " ssl handshake failed:/" + tuple3.getValue1() + ":" + tuple3.getValue2();
                logger.debug(" SslHandler is null, host: {}, port: {}", tuple3.getValue1(), tuple3.getValue2());
                errorMessageList.add(sslHandshakeFailedMessage);
                continue;
            }
            Future<Channel> sshHandshakeFuture = sslhandler.handshakeFuture().awaitUninterruptibly();
            if (sshHandshakeFuture.isSuccess()) {
                atLeastOneConnectSuccess = true;
                logger.trace(" ssl handshake success {}:{}", tuple3.getValue1(), tuple3.getValue2());
            } else {
                String sslHandshakeFailedMessage = " ssl handshake failed:/" + tuple3.getValue1() + ":" + tuple3.getValue2();
                errorMessageList.add(sslHandshakeFailedMessage);
            }
        }
    }
    // All connections failed
    if (!atLeastOneConnectSuccess) {
        logger.error(" all connections have failed, " + errorMessageList.toString());
        throw new RuntimeException(" Failed to connect to nodes: " + errorMessageList.toString() + helpInfo);
    }
    running = true;
    logger.debug(" start connect end. ");
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ArrayList(java.util.ArrayList) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext) ChannelFuture(io.netty.channel.ChannelFuture) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) SslHandler(io.netty.handler.ssl.SslHandler) BigInteger(java.math.BigInteger) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Tuple3(org.fisco.bcos.web3j.tuples.generated.Tuple3) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor)

Example 44 with IdleStateHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project summer by foxsugar.

the class SocketServerInitializer method initChannel.

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }
    // p.addLast(new LoggingHandler(LogLevel.INFO));
    p.addLast("encoder", new GameCharsEncoder());
    p.addLast("decoder", new GameCharsDecoder());
    p.addLast("timeout", new IdleStateHandler(15, 0, 0, TimeUnit.SECONDS));
    // p.addLast(new SocketHandler());
    p.addLast("gameHandler", new GameMsgHandler());
}
Also used : GameCharsDecoder(com.code.server.gate.encoding.GameCharsDecoder) GameMsgHandler(com.code.server.gate.handle.GameMsgHandler) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) GameCharsEncoder(com.code.server.gate.encoding.GameCharsEncoder) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 45 with IdleStateHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project dubbo by alibaba.

the class QosProcessHandler method decode.

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 1) {
        return;
    }
    // read one byte to guess protocol
    final int magic = in.getByte(in.readerIndex());
    ChannelPipeline p = ctx.pipeline();
    p.addLast(new LocalHostPermitHandler(acceptForeignIp));
    if (isHttp(magic)) {
        // no welcome output for http protocol
        if (welcomeFuture != null && welcomeFuture.isCancellable()) {
            welcomeFuture.cancel(false);
        }
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpProcessHandler());
        p.remove(this);
    } else {
        p.addLast(new LineBasedFrameDecoder(2048));
        p.addLast(new StringDecoder(CharsetUtil.UTF_8));
        p.addLast(new StringEncoder(CharsetUtil.UTF_8));
        p.addLast(new IdleStateHandler(0, 0, 5 * 60));
        p.addLast(new TelnetIdleEventHandler());
        p.addLast(new TelnetProcessHandler());
        p.remove(this);
    }
}
Also used : StringEncoder(io.netty.handler.codec.string.StringEncoder) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelPipeline(io.netty.channel.ChannelPipeline)

Aggregations

IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)70 ChannelPipeline (io.netty.channel.ChannelPipeline)35 SocketChannel (io.netty.channel.socket.SocketChannel)18 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)14 LoggingHandler (io.netty.handler.logging.LoggingHandler)14 SslHandler (io.netty.handler.ssl.SslHandler)14 ChunkedWriteHandler (io.netty.handler.stream.ChunkedWriteHandler)12 ChannelFuture (io.netty.channel.ChannelFuture)10 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)10 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)9 Bootstrap (io.netty.bootstrap.Bootstrap)8 EventLoopGroup (io.netty.channel.EventLoopGroup)8 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)7 HttpServerCodec (io.netty.handler.codec.http.HttpServerCodec)7 IdleStateEvent (io.netty.handler.timeout.IdleStateEvent)7 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)6 Channel (io.netty.channel.Channel)6 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)6 SslContext (io.netty.handler.ssl.SslContext)6 InetSocketAddress (java.net.InetSocketAddress)6